pthread 執行緒立即取消的兩種方法
1.相關函式介紹
a.
int pthread_cancel(pthread_t thread)
傳送終止訊號給thread執行緒,如果成功則返回0,否則為非0值。傳送成功並不意味著thread會終止。
b.
int pthread_setcancelstate(int state, int *oldstate)
設定本執行緒對Cancel訊號的反應,state有兩種值:PTHREAD_CANCEL_ENABLE(預設)和PTHREAD_CANCEL_DISABLE,
分別表示收到訊號後設為CANCLED狀態和忽略CANCEL訊號繼續執行;old_state如果不為NULL則存入原來的Cancel狀態以便恢復。
c.
int pthread_setcanceltype(int type, int *oldtype)
設定本執行緒取消動作的執行時機,type由兩種取值:PTHREAD_CANCEL_DEFFERED和PTHREAD_CANCEL_ASYCHRONOUS,僅當Cancel狀態為Enable時有效,分別表示收到訊號後繼續執行至下一個取消點再退出和立即執行取消動作(退出);oldtype如果不為NULL則存入運來的取消動作型別值。
d.
void pthread_testcancel(void)
是說pthread_testcancel在不包含取消點,但是又需要取消點的地方建立一個取消點,以便在一個沒有包含取消點的執行程式碼執行緒中響應取消請求.
執行緒取消功能處於啟用狀態且取消狀態設定為延遲狀態時,pthread_testcancel()函式有效。
如果在取消功能處處於禁用狀態下呼叫pthread_testcancel(),則該函式不起作用。
請務必僅線上程取消執行緒操作安全的序列中插入pthread_testcancel()。除通過pthread_testcancel()呼叫以程式設計方式建立的取消點意外,pthread標準還指定了幾個取消點。測試退出點,就是測試cancel訊號.
e.
int pthread_join(pthread_t thread, void **value_ptr);
thread:等待退出執行緒的執行緒號。
value_ptr:退出執行緒的返回值。
1.同步取消執行緒
程式碼示例:
#include<stdio.h>
#include<stdlib.h>
#include <pthread.h>
void *thread_fun(void *arg)
{
int i=1;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL );
/*同步取消,等到下一個取消點再取消*/
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
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;
}
2.非同步取消執行緒
示例程式碼:
#include<stdio.h>
#include<stdlib.h>
#include <pthread.h>
void *thread_fun(void *arg)
{
int i=1;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
/*同步取消,等到下一個取消點再取消*/
// pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
/*非同步取消, 執行緒接到取消訊號後,立即退出*/
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
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;
}
程式碼編譯:
gcc pthread_test.c -o pthread_test -lpthread