pthread_exit函數
將單個線程退出
?????? void pthread_exit(void *retval);?? 參數:retval表示線程退出狀態,通常傳NULL
思考:使用exit將指定線程退出,可以嗎??????????????????????????????????????????????????????????? ????????????? 【pthrd_exit.c】
?????? 結論:線程中,禁止使用exit函數,會導致進程內所有線程全部退出。
?????? 在不添加sleep控制輸出順序的情況下。pthread_create在循環中,幾乎瞬間創建5個線程,但只有第1個線程有機會輸出(或者第2個也有,也可能沒有,取決于內核調度)如果第3個線程執行了exit,將整個進程退出了,所以全部線程退出了。
?????? 所以,多線程環境中,應盡量少用,或者不使用exit函數,取而代之使用pthread_exit函數,將單個線程退出。任何線程里exit導致進程退出,其他線程未工作結束,主控線程退出時不能return或exit。
另注意,pthread_exit或者return返回的指針所指向的內存單元必須是全局的或者是用malloc分配的,不能在線程函數的棧上分配,因為當其它線程得到這個返回指針時線程函數已經退出了。
【練習】:編寫多線程程序,總結exit、return、pthread_exit各自退出效果。
?????? return:返回到調用者那里去。
?????? pthread_exit():將調用該函數的線程?????????????
?????? exit: 將進程退出。
/*** exit.c ***/ #include<stdio.h> #include<string.h> #include<unistd.h> #include<stdlib.h> #include<pthread.h>void *thrd_func(void *arg) {printf("th thread: thread id = %lu, pid = %u\n",pthread_self(),getpid());return NULL; }int main() {pthread_t tid;int ret,i;// for(i = 0; i < 5; i++) {ret = pthread_create(&tid,NULL,thrd_func,(void *)&i);if(0 != ret){fprintf(stderr,"pthread_create error:%s\n",strerror(ret));exit(1);}}printf("In main2: thread id = %lu,pid = %u\n",pthread_self(),getpid());pthread_exit((void*)1); }
運行結果:
ubuntu1604@ubuntu:~/wangqinghe/linux/20190819$ ./exit
In main2: thread id = 139958373693184,pid = 12073
th thread: thread id = 139958365353728, pid = 12073
/*** tfn.c ***/ #include<stdio.h> #include<string.h> #include<unistd.h> #include<stdlib.h> #include<pthread.h>void *tfn(void *arg) {int i = *((int*)arg);printf("%dth thread: thread id = %lu, pid = %u\n",i+1,pthread_self(),getpid());return NULL; }int main() {pthread_t tid;int ret,i;for(i = 0; i < 5; i++){ret = pthread_create(&tid,NULL,tfn,(void *)&i);if(0 != ret){fprintf(stderr,"pthread_create error:%s\n",strerror(ret));exit(1);}}printf("In main2: thread id = %lu,pid = %u\n",pthread_self(),getpid());pthread_exit(NULL); }
ubuntu1604@ubuntu:~/wangqinghe/linux/20190819$ ./tfn
In main2: thread id = 140606869358336,pid = 12102
6th thread: thread id = 140606827448064, pid = 12102
6th thread: thread id = 140606835840768, pid = 12102
6th thread: thread id = 140606844233472, pid = 12102
6th thread: thread id = 140606861018880, pid = 12102
6th thread: thread id = 140606852626176, pid = 12102