最近不少精力在Linux上,今天簡單看了一下Linux上的線程和同步,其實無論windows仍是Linux,OS層面的不少原理和概念都是相同的,不少windows之上的經驗和概念徹底能夠移植到Linux上。ios
今天用到了建立線程和一個阻塞式的線程同步函數。windows
用到的幾個函數函數
#include <pthread.h> //建立線程 int pthread_create( pthread_t* thread, /*線程標ID, pthread_t pthread_self(void) 可獲取當前線程ID*/ pthread_attr_t* attr, /*線程屬性,如無須要可爲0 */ void* (*start_routine)(void*), /*線程函數*/ void* arg /*線程函數參數*/ ); 返回值 成功: 0 失敗:錯誤代碼 //終止線程 void pthread_exit( void* retval /*線程返回時帶回的值,注意局部變量等問題*/ ) //阻塞式線程同步 int pthread_join( pthread_t th, /*pthread_create 函數第一個參數帶回的值*/ void** thread /*線程函數返回值,內存在此函數內部分配*/ ) //獲取當前線程ID pthread_t pthread_self(void)
貼出代碼oop
/*a demo for Linux MultiThread */ 3 #include <iostream> 4 #include <pthread.h> 5 #include <stdlib.h> 6 #include <unistd.h> 7 using namespace std; 8 9 //thread function 10 void* start_routine(void* p) 11 { 12 if (0 == p) 13 return 0; 14 15 size_t nLoops = *( (size_t*) p ); 16 17 for (size_t i = 0; i < nLoops; ++ i) 18 { 19 cout << i << endl; 20 usleep(1000 * 800); //800 ms 21 } 22 23 cout << endl << "This thread ID is " << pthread_self() << endl; 24 25 return 0; 26 } 27 28 29 int main() 30 { 31 pthread_t ptThread1; 32 size_t* pLoops = new size_t(10); 33 int nRet = pthread_create(&ptThread1, 0, start_routine, (void*)pLoops); 34 if (0 != nRet) 35 cerr << endl << "create thread error!" << endl; 36 else 37 cerr << endl << "create thread successfully, return value code is " << nRet \ 38 << endl << "thread ID is " << ptThread1 << endl; 39 40 if (0 == nRet) 41 { 42 cout << endl << "wait for thread " << ptThread1 << endl; 43 void* pRetVal = 0; 44 int nJoinRet = pthread_join(ptThread1, (void**)&pRetVal); 45 cout << endl << "thread " << ptThread1 << " finished !" << endl; 46 cout << "thread return value is " << (char*)pRetVal << endl; 47 } 48 cout << endl; 49 50 delete pLoops; 51 pLoops = 0; 52 53 system("ls"); 54 55 return 0; 56 }
執行結果spa
PS: 注意可能須要在g++編譯參數上加上 -lpthread線程