linux下pthread_cancel無法取消線程的原因【轉】

來源:互聯網
上載者:User

標籤:keyword   bar   著作權   enter   include   art   alt   data   分享圖片   

轉自:http://blog.csdn.net/huangshanchun/article/details/47420961

著作權聲明:歡迎轉載,如有不足之處,懇請斧正。

一個線程可以調用pthread_cancel終止同一進程中的另一個線程,但是值得強調的是:同一進程的線程間,pthread_cancel向另一線程發終止訊號。系統並不會馬上關閉被取消線程,只有在被取消線程下次系統調用時,才會真正結束線程。或調用pthread_testcancel,讓核心去檢測是否需要取消當前線程。被取消的線程,退出值,定義在Linux的pthread庫中常數PTHREAD_CANCELED的值是-1。

[cpp] view plain copy
  1. #include <pthread.h>  
  2.   
  3. int pthread_cancel(pthread_t thread);  


看下面程式:

[cpp] view plain copy
  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. #include <pthread.h>  
  4. void *thread_fun(void *arg)  
  5. {  
  6.     int i=1;  
  7.     printf("thread start \n");  
  8.     while(1)  
  9.     {  
  10.         i++;  
  11.     }  
  12.     return (void *)0;  
  13. }  
  14. int main()  
  15. {  
  16.     void *ret=NULL;  
  17.     int iret=0;  
  18.     pthread_t tid;  
  19.     pthread_create(&tid,NULL,thread_fun,NULL);  
  20.     sleep(1);  
  21.       
  22.     pthread_cancel(tid);//取消線程  
  23.     pthread_join(tid, &ret);  
  24.     printf("thread 3 exit code %d\n", (int)ret);  
  25.       
  26.     return 0;  
  27.       
  28. }  


會發現程式再一直運行,線程無法被取消,究其原因pthread_cancel向另一線程發終止訊號。系統並不會馬上關閉被取消線程,只有在被取消線程下次系統調用時,才會真正結束線程。如果線程裡面沒有執行系統調用,可以使用pthread_testcancel解決。

[cpp] view plain copy
  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. #include <pthread.h>  
  4. void *thread_fun(void *arg)  
  5. {  
  6.     int i=1;  
  7.     printf("thread start \n");  
  8.     while(1)  
  9.     {  
  10.         i++;  
  11.         pthread_testcancel();  
  12.     }  
  13.     return (void *)0;  
  14. }  
  15. int main()  
  16. {  
  17.     void *ret=NULL;  
  18.     int iret=0;  
  19.     pthread_t tid;  
  20.     pthread_create(&tid,NULL,thread_fun,NULL);  
  21.     sleep(1);  
  22.       
  23.     pthread_cancel(tid);//取消線程  
  24.     pthread_join(tid, &ret);  
  25.     printf("thread 3 exit code %d\n", (int)ret);  
  26.       
  27.     return 0;  
  28.       
  29. }  


linux下pthread_cancel無法取消線程的原因【轉】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.