线程退出
pthread_exit函數(shù)
將單個線程退出
?????? void pthread_exit(void *retval);?? 參數(shù):retval表示線程退出狀態(tài),通常傳NULL
思考:使用exit將指定線程退出,可以嗎??????????????????????????????????????????????????????????? ????????????? 【pthrd_exit.c】
?????? 結(jié)論:線程中,禁止使用exit函數(shù),會導(dǎo)致進(jìn)程內(nèi)所有線程全部退出。
?????? 在不添加sleep控制輸出順序的情況下。pthread_create在循環(huán)中,幾乎瞬間創(chuàng)建5個線程,但只有第1個線程有機(jī)會輸出(或者第2個也有,也可能沒有,取決于內(nèi)核調(diào)度)如果第3個線程執(zhí)行了exit,將整個進(jìn)程退出了,所以全部線程退出了。
?????? 所以,多線程環(huán)境中,應(yīng)盡量少用,或者不使用exit函數(shù),取而代之使用pthread_exit函數(shù),將單個線程退出。任何線程里exit導(dǎo)致進(jìn)程退出,其他線程未工作結(jié)束,主控線程退出時不能return或exit。
另注意,pthread_exit或者return返回的指針?biāo)赶虻膬?nèi)存單元必須是全局的或者是用malloc分配的,不能在線程函數(shù)的棧上分配,因為當(dāng)其它線程得到這個返回指針時線程函數(shù)已經(jīng)退出了。
【練習(xí)】:編寫多線程程序,總結(jié)exit、return、pthread_exit各自退出效果。
?????? return:返回到調(diào)用者那里去。
?????? pthread_exit():將調(diào)用該函數(shù)的線程?????????????
?????? exit: 將進(jìn)程退出。
/*** 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); }運(yùn)行結(jié)果:
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
轉(zhuǎn)載于:https://www.cnblogs.com/wanghao-boke/p/11389699.html
總結(jié)
- 上一篇: 成都欢乐谷凭准考证买票需不需要身份证
- 下一篇: 小米盒子4和小米盒子4C有什么区别