pthread 是 POSIX threads 的簡(jiǎn)稱泳炉,POSIX 線程是一個(gè) POSIX 標(biāo)準(zhǔn)線程笆呆。
該標(biāo)準(zhǔn)定義內(nèi)部API創(chuàng)建和操作線程相寇。
1声诸、創(chuàng)建
通過 pthread_create() 創(chuàng)建線程
int pthread_create( pthread_t * thread, const pthread_attr_t, void * (*start_function) ( void *), void * args )
2、參數(shù)
2.1围苫、pthread_create 參數(shù)理解
第一個(gè)參數(shù):線程ID指針裤园,本質(zhì)上是線程ID 的寫入地址
第二個(gè)參數(shù):線程屬性參數(shù)
第三個(gè)參數(shù):線程運(yùn)行函數(shù)func的地址
第四個(gè)參數(shù):線程運(yùn)行函數(shù)func的參數(shù)
進(jìn)一步說明:
(1)第一個(gè)參數(shù)是pthread_t類型指針,宏pthread_t 原型是 unsigned int剂府,用于存儲(chǔ)線程ID
(2)第三個(gè)參數(shù) void * (*start_function) ( void *) 含義是指向返回值為 void * 拧揽,參數(shù)類型為 void * 的函數(shù)指針
2.2、pthread_create 返回值理解
pthread_create 返回一個(gè)int值腺占,線程創(chuàng)建成功時(shí)返回0淤袜;其他值都表示創(chuàng)建線程發(fā)生錯(cuò)誤。
這里容易誤解為返回線程ID衰伯,其實(shí)不是铡羡。
3、編譯
編譯的時(shí)候需要帶有 -pthread
舉例:g++ -pthread -o cpp_multi cpp_multi.cpp
4意鲸、實(shí)驗(yàn)
pthread_t* p_arr = (pthread_t* ) malloc(THREAD_NUM * sizeof(pthread_t));