zoukankan      html  css  js  c++  java
  • linux下pthread_cancel无法取消线程的原因【转】

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

    一个线程可以调用pthread_cancel终止同一进程中的另一个线程,但是值得强调的是:同一进程的线程间,pthread_cancel向另一线程发终止信号。系统并不会马上关闭被取消线程,只有在被取消线程下次系统调用时,才会真正结束线程。或调用pthread_testcancel,让内核去检测是否需要取消当前线程。被取消的线程,退出值,定义在Linux的pthread库中常数PTHREAD_CANCELED的值是-1。

    1. #include <pthread.h>  
    2.   
    3. int pthread_cancel(pthread_t thread);  


    看下面程序:

    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  ");  
    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 ", (int)ret);  
    25.       
    26.     return 0;  
    27.       
    28. }  


    会发现程序再一直运行,线程无法被取消,究其原因pthread_cancel向另一线程发终止信号。系统并不会马上关闭被取消线程,只有在被取消线程下次系统调用时,才会真正结束线程。如果线程里面没有执行系统调用,可以使用pthread_testcancel解决。

    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  ");  
    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 ", (int)ret);  
    26.       
    27.     return 0;  
    28.       
    29. }  


  • 相关阅读:
    homework2
    一件关于Bug的小事
    软件测试作业三:有关控制流图、覆盖内容
    用CSS改变select框的样式
    lab1--ideal + junit
    软件测试作业二
    记一次曾经项目中遇到的错误
    02组_现代软件工程_第04次作业——利用4象限原理分析自身CanTool项目的构成
    02组_现代软件工程_第03次作业——对于自身评价(原有水平以及长远目标分析总结)
    02组_现代软件工程_第02次作业——初谈GitHub使用详解以及设计
  • 原文地址:https://www.cnblogs.com/sky-heaven/p/8031366.html
Copyright © 2011-2022 走看看