日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

线程退出

發布時間:2023/11/30 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程退出 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

轉載于:https://www.cnblogs.com/wanghao-boke/p/11389699.html

總結

以上是生活随笔為你收集整理的线程退出的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。