调用pthread_cancel阻塞问题解决方法.

两个例子:

阻塞例子:

    #include<stdio.h>  
    #include<stdlib.h>  
    #include <pthread.h>  
    #include <unistd.h>
    void *thread_fun(void *arg)  
    {  
        int i=1;  
        printf("thread start \n");  
        while(1)  
        {  
            i++;  
        }  
        return (void *)0;  
    }  
    int main()  
    {  
        void *ret=NULL;  
        int iret=0;  
        pthread_t tid;  
        pthread_create(&tid,NULL,thread_fun,NULL);  
        sleep(1);  
          
        pthread_cancel(tid);//取消线程  
        pthread_join(tid, &ret);  
        printf("thread 3 exit code %p\n", ret);  
          
        return 0;  
          
    }  

非阻塞例子:

    #include<stdio.h>  
    #include<stdlib.h>  
    #include <pthread.h>  
    #include <unistd.h>
    void *thread_fun(void *arg)  
    {  
        int i=1;  
        printf("thread start \n");  
        while(1)  
        {  
            i++;  
            //pthread_testcancel(); //没有系统调用的时候需要它停掉线程. 否则线程会一直阻塞.
            //printf("%d \n", i); //系统调用函数,则不用上面函数将其停掉.
            //sleep(1);
        }  
        return (void *)0;  
    }  
    int main()  
    {  
        void *ret=NULL;  
        int iret=0;  
        pthread_t tid;  
        pthread_create(&tid,NULL,thread_fun,NULL);  
        sleep(5);  
          
        pthread_cancel(tid);//取消线程  
        pthread_join(tid, &ret);  
        printf("thread 3 exit code %p\n", ret);  
          
        return 0;  
          
    }  

将while循环中的注释掉的三句,任何一句打开,都会停止阻塞.

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

必须要有系统调用, 如果没有系统调用,则调用pthread_testcancel函数.

pthread_testcancel()函数用来在当前线程创建一个“可取消点”。如果当前线程是不能取消的,则这个函数无效。pthread_setcancelstate, pthread_setcanceltype, pthread_testcancel - set cancelability state这三个函数用来设置线程是否可以被其他线程调用pthread_cancel函数取消/终止。

拷贝链接:

 http://blog.csdn.net/i_am_jojo/article/details/7594174

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值