天天看點

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

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

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

#include <pthread.h>  

int pthread_cancel(pthread_t thread);  

看下面程式:

#include<stdio.h>  

#include<stdlib.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 %d\n", (int)ret);  

    return 0;  

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

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

        pthread_testcancel();  

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

本文轉自張昺華-sky部落格園部落格,原文連結:http://www.cnblogs.com/sky-heaven/p/8031366.html,如需轉載請自行聯系原作者

繼續閱讀