pthread 是 POSIX threads 的簡稱,POSIX 線程是一個 POSIX 標準線程。
該標準定義內部API創建和操作線程。
1、創建
通過 pthread_create() 創建線程
int pthread_create( pthread_t * thread, const pthread_attr_t, void * (*start_function) ( void *), void * args )
2、參數
2.1、pthread_create 參數理解
第一個參數:線程ID指針,本質上是線程ID 的寫入地址
第二個參數:線程屬性參數
第三個參數:線程運行函數func的地址
第四個參數:線程運行函數func的參數
進一步說明:
(1)第一個參數是pthread_t類型指針,宏pthread_t 原型是 unsigned int,用于存儲線程ID
(2)第三個參數 void * (*start_function) ( void *) 含義是指向返回值為 void * ,參數類型為 void * 的函數指針
2.2、pthread_create 返回值理解
pthread_create 返回一個int值,線程創建成功時返回0;其他值都表示創建線程發生錯誤。
這里容易誤解為返回線程ID,其實不是。
3、編譯
編譯的時候需要帶有 -pthread
舉例:g++ -pthread -o cpp_multi cpp_multi.cpp
4、實驗
pthread_t* p_arr = (pthread_t* ) malloc(THREAD_NUM * sizeof(pthread_t));
main
thread_func
result