Linux系統——線程建立pthread_create()
實作代碼
#include<bits/stdc++.h>
#include<unistd.h>
#include<pthread.h>
void* func(void *arg) {
printf("Child thread!\n");
printf("Thread ID is %ld\n", (unsigned long) pthread_self());
return 0;
}
int main(int argc, char const* argv[]) {
pthread_t threadId;
if(pthread_create(&threadId, NULL,func, NULL) == -1) {
printf("Thread create error!\n");
exit(1);
}
sleep(2);
exit(0);
}
注意
-
sleep()函數
上述代碼需要調用sleep()函數使主線程陷入阻塞,否則主線程執行結束導緻程序結束,進而導緻子線程未執行完強行退出,得到意料之外的結果
-
pthread_join()函數
可以用pthead_join()函數代替sleep(),使主線程等待子線程
- 編譯過程
g++ -pthread pthreadCreateTest.cpp -o pthreadCreateTest
./pthreadCreateTest
pthread_create()
-
傳回值
傳回0則為成功,-1則為失敗
-
函數聲明
int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,
void *(start_rtn)(void),void *arg);
第一個參數為線程ID,第二個參數預設為線程屬性一般置為NULL,第三個參數為函數指針,指向線程要執行的函數,第四個參數為傳給第三個函數指針的參數
pthread_self()
-
傳回值
傳回目前線程ID
-
函數聲明
pthread_t pthread_self(void);
最後
- 由于部落客水準有限,不免有疏漏之處,歡迎讀者随時批評指正,以免造成不必要的誤解!