Linux下多執行緒建立
阿新 • • 發佈:2022-03-17
1.pthread_create
Linux中執行緒建立用pthread_create函式
#include <pthread.h> int pthread_create(
pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg );
引數:
1.指向執行緒識別符號的指標
2.指向執行緒屬性的指標
3.指向執行緒函式的指標,該函式返回值型別和引數型別均為void *
4.指向執行緒函式引數的指標
返回值:
成功建立返回0
建立失敗返回錯誤編號
一個簡單的例子:
#include <stdio.h> #include <pthread.h> #include <unistd.h>
void* func(void* param) { printf("Child thread ...\n"); pthread_exit(0); } int main(void) { pthread_t tid; pthread_create(&tid,NULL,func,NULL); sleep(1); return 0; }
因為pthread並非Linux系統的預設庫,所以在編譯時注意加上-lpthread
引數,以呼叫靜態連結庫。
pthread_exit()函式是執行緒退出函式。注意,主執行緒加了sleep(1),這是讓主執行緒等待1秒,讓子執行緒執行完。如果沒有的話,很可能看不到輸出,這是因為子執行緒沒執行完,父執行緒可能已經退出了,影響子執行緒的執行。
2.pthread_join
上面用到sleep()函式讓父執行緒等待子執行緒。但是執行緒中通常使用pthread_join函式,讓父執行緒等待子執行緒執行完
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
引數:執行緒號,指向返回值的指標
返回值:成功返回0,失敗返回錯誤編號
一個例子:給子執行緒傳遞一個數x,計算並返回1+2+...+x的結果,讓父程序輸出
#include <stdio.h> #include <pthread.h> void* func(void* param) { int x = *(int *)param; int sum = 0; for(int i=1;i<=x;i++) { sum+=i; } return (void *)sum; } int main(void) { pthread_t tid; int x = 10; pthread_create(&tid,NULL,func,(void *)&x); void* sum; pthread_join(tid,&sum); printf("sum = %d\n",(int)sum); return 0; }