pthread_create函數? ? ? ??
????????pthread_create
?是 POSIX 線程庫(pthread)中的一個函數,用于創建一個新的線程。
頭文件
#include <pthread.h>
函數原型
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
參數說明
? ? ? ? thread:新線程創建成功后,新線程的標識符。
? ? ? ? attr:設置線程屬性,一般不需要特殊的屬性,直接NULL即可
? ? ? ? start_routine:線程的函數,線程啟動后需要執行的函數(回調函數)
? ? ? ? arg:傳給線程啟動函數的參數
返回值
????????如果?pthread_create
?成功創建了新線程,它將返回?0
。
????????如果創建線程失敗,它將返回一個非零的錯誤碼,用于表示具體的錯誤原因。
示例
#include <iostream>
#include <pthread.h>
#include <unistd.h>using namespace std;// 線程回調函數
void* thread_function(void* v)
{int num = *(int*)v;while(1){cout << "thread process" << num << endl;sleep(1);}
}int main()
{pthread_t thread_id;int num = 100;// 創建新線程pthread_create(&thread_id, NULL, thread_function, &num);while (1){cout << "main process" << endl;sleep(1);}return 0;
}