線程取消選項涉及以下函數運用
1.int pthread_cancel(pthread_t tid)
2.int ptnread_setcancelstate(int state, int *oldstate)
3.void pthread_testcancel(void)
4.int pthread_setcanceltype(int type, int *oldtype)
舉例運用------->基於<<UNIX 環境高級編程>>例子 做的改動
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int oldstate,oldtype;
void *
thr_fn1(void *arg)
{
printf("thread 1 returning\n");
return((void *)1);
}
void *
thr_fn2(void *arg)
{
/*pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&oldstate);*/
/*pthread_testcancel();*/
/*pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype);*/
printf("thread 2 returning\n");
pthread_exit((void *)2);
}
int
main(void)
{
int err;
pthread_t tid1, tid2;
void *tret;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if (err != 0)
printf("can't create thread 1: %s\n", strerror(err));
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if (err != 0)
printf("can't create thread 2: %s\n", strerror(err));
if(!(pthread_cancel(tid2)))
{
sleep(1);
/*printf("oldstate:value=%d address=0x%x\n",oldstate,&oldstate);*/
/*printf("oldtype:value=%d address=0x%x\n",oldtype,&oldtype);*/
printf("pthread_cancel success!\n");
}
else
{ sleep(1);
printf("pthread_cancel Failed!\n");
}
err = pthread_join(tid1, &tret);
if (err != 0)
printf("can't join with thread 1: %s\n", strerror(err));
printf("thread 1 exit code %d\n", (int)tret);
err = pthread_join(tid2, &tret);
if (err != 0)
printf("can't join with thread 2: %s\n", strerror(err));
printf("thread 2 exit code %d\n", (int)tret);
exit(0);
}
爲了便於說明,假設
1代表pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&oldstate)
2代表pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype);
3代表pthread_testcancel();
4代表printf("oldstate:value=%d address=0x%x\n",oldstate,&oldstate);
5代表printf("oldtype:value=%d address=0x%x\n",oldtype,&oldtype);
下面說明註釋掉不同的代碼打印的結果
第一種 在程序註釋掉這所有的5條代碼
打印如下:
我們結合程序和打印結果觀察 ,可知線程2在接收到主線程的取消請求後,
並不馬上停下會繼續運行直到到達某個取消點。線程2中可看到它已經執行了 printf("thread 2 returning\n"),取消點纔到來。
第二種 使上面第三條代碼有效
打印如下:
與第一種情況對比,我們在打印前設置了pthread_testcancel(),該函數的作用是在程序中自己添加取消點。所有線程2中還沒打印就已經被取消了。
第三種 使上面1.4代碼有效
打印如下:
與第一種情況相比, pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&oldstate)使pthread_cancel無效了,所有能完成退出,並且pthread_join能正確的獲得的退出狀態。
第四種 使上面2.5代碼有效
打印如下:
與第一種情況相比,我在線程2打印前面添加了 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype),它的作用是設置線程爲異步取消,通俗點就是在運行了此函數後馬上取消,不受取消點的影響(此處跟第二種情況有點一樣)。通過第一種
我們知道線程2的取消點是在打印了之後的某個時刻。