void pthread_exit(void * rval_ptr)
線程退出函數 其他線程可以通過 pthread_jion 得到這個 無類型指針 rval_ptr
int pthread_join (pthread_t tid, void **rval_ptr)
等待線程 tid 終止,調用線程將阻塞,直到 線程 tid 調用 pthrad_exit, 返回,或者被取消。 rval_ptr就是調用 exit 的參數,如果對返回值不感興趣, 可以傳遞NULL
一下程序在 開啟的第奇數個線程的時候,會sleep 相應的秒數,運行時,主線程由於調用 pthread_join 阻塞,可以看到標准輸出會卡。
1 #include <pthread.h>
2 #include <unistd.h>
3 #include <stdio.h>
4 struct args{
5 char name[10];
6 int exit_code;
7 };
8
9 void * thread_run(void *arg){
10 struct args* a = (struct args*)arg;
11 printf("%s run, id:%u
", a->name, (unsigned int)(pthread_self())); // use arg to get the params;
12 if(a->exit_code % 2){
13 sleep(a->exit_code); // make the thread sleep some second;
14 printf("im thread %d, here sleep %d second!
", a->exit_code, a->exit_code);
15 }
16 pthread_exit((void*)(&(a->exit_code)));
17 }
18
19 int main(){
20 pthread_t tid[10]; //thread_ids
21 struct args a[10]; //thread_functions args
22 void *ec; //exit code
23 int i;
24 for(i = 0; i < 10; ++i){
25 a[i].name[0] = ;
26 sprintf(a[i].name, "thread_%d", i);
27 a[i].exit_code = i;
28 if(pthread_create(&tid[i], NULL, thread_run, (void *)(&a[i]))){ //call pthread_create to create a thread use arg[i]
29 printf("error");
30 return 0;
31 }
32 }
33 for(i = 0; i < 10; ++i){
34 pthread_join(tid[i], &ec);//wait for thread tid[i] stop;
35 printf("%s exit code is:%d
", a[i].name, (*(int*)ec));
36 }
37 return 0;
38 }
39
編譯 :
g++ ./pthread_exit.cpp -lpthread -opthread_exit
結果:
thread_0 run, id:968255760
thread_2 run, id:951470352
thread_1 run, id:959863056
thread_3 run, id:943077648
thread_4 run, id:934684944
thread_5 run, id:926292240
thread_6 run, id:917899536
thread_7 run, id:909506832
thread_8 run, id:901114128
thread_9 run, id:892721424
thread_0 exit code is:0
im thread 1, here sleep 1 second!
thread_1 exit code is:1
thread_2 exit code is:2
im thread 3, here sleep 3 second!
thread_3 exit code is:3
thread_4 exit code is:4
im thread 5, here sleep 5 second!
thread_5 exit code is:5
thread_6 exit code is:6
im thread 7, here sleep 7 second!
thread_7 exit code is:7
thread_8 exit code is:8
im thread 9, here sleep 9 second!
thread_9 exit code is:9