一個線程能夠調用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> #include <pthread.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; }

會發現程序再一直執行。線程無法被取消,究其原因pthread_cancel向還有一線程發終止信號。系統並不會立即關閉被取消線程,僅僅有在被取消線程下次系統調用時,才會真正結束線程。
假設線程里面沒有執行系統調用。能夠使用pthread_testcancel解決。
#include<stdio.h> #include<stdlib.h> #include <pthread.h> void *thread_fun(void *arg) { int i=1; printf("thread start \n"); while(1) { i++; pthread_testcancel(); } 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; }
