pthread_cancel、pthread_equal函数
(1)pthread_cancel函數(shù)
int pthread_cancel(pthread_t thread);??? 成功:0;失敗:錯(cuò)誤號(hào)
作用:殺死(取消)線程,其作用對應(yīng)進(jìn)程中 kill() 函數(shù)。
注意:線程的取消并不是實(shí)時(shí)的,而有一定的延時(shí)。需要等待線程到達(dá)某個(gè)取消點(diǎn)(檢查點(diǎn))。殺死線程不是立刻就能完成,必須要到達(dá)取消點(diǎn)。取消點(diǎn):是線程檢查是否被取消,并按請求進(jìn)行動(dòng)作的一個(gè)位置。通常是一些系統(tǒng)調(diào)用creat,open,pause,close,read,write等等。執(zhí)行命令man 7 pthreads可以查看具備這些取消點(diǎn)的系統(tǒng)調(diào)用列表。也可參閱 APUE.12.7 取消選項(xiàng)小節(jié)。
可粗略認(rèn)為一個(gè)系統(tǒng)調(diào)用(進(jìn)入內(nèi)核)即為一個(gè)取消點(diǎn)。如線程中沒有取消點(diǎn),可以通過調(diào)用pthread_testcancel( )函數(shù)自行設(shè)置一個(gè)取消點(diǎn),即在子線程的執(zhí)行的函數(shù)中調(diào)用該函數(shù)即可:pthread_testcancel( );? 該函數(shù)是庫函數(shù),但執(zhí)行該庫函數(shù)需要進(jìn)一步使用系統(tǒng)調(diào)用,從而到達(dá)檢查點(diǎn)。只要線程到達(dá)檢查點(diǎn),如果有其它線程對其調(diào)用了pthread_cancel函數(shù),則該線程就會(huì)自動(dòng)終止。
被取消的線程,退出值為常數(shù)PTHREAD_CANCELED的值是-1。可在頭文件pthread.h中找到它的定義:#define PTHREAD_CANCELED ((void *) -1)。因此當(dāng)我們對一個(gè)已經(jīng)被取消的線程使用pthread_join回收時(shí),得到的返回值為-1。
//終止線程的三種方法。注意“取消點(diǎn)”的概念。
#include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h>void *tfn1(void *arg) //方法1:retun {printf("thread 1 returning\n");return (void *)111; }void *tfn2(void *arg) //方法2:pthread_exit {printf("thread 2 exiting\n");pthread_exit((void *)222); }void *tfn3(void *arg) //方法三:pthread_cancel {while (1) {printf("thread 3: I'm going to die in 3 seconds ...\n"); //取消點(diǎn)sleep(1); //同樣是取消點(diǎn) //pthread_testcancel(); //自己添加取消點(diǎn)}return (void *)666; }int main(void) {pthread_t tid;void *tret = NULL;pthread_create(&tid, NULL, tfn1, NULL);pthread_join(tid, &tret);printf("thread 1 exit code = %d\n\n", (int)tret);pthread_create(&tid, NULL, tfn2, NULL);pthread_join(tid, &tret);printf("thread 2 exit code = %d\n\n", (int)tret);pthread_create(&tid, NULL, tfn3, NULL);sleep(3);pthread_cancel(tid);pthread_join(tid, &tret);printf("thread 3 exit code = %d\n", (int)tret);return 0; }[root@localhost 01_pthread_test]# ./pthrd_endof3
thread 1 returning
thread 1 exit code = 111
?
thread 2 exiting
thread 2 exit code = 222
?
thread 3: I'm going to die in 3 seconds ...
thread 3: I'm going to die in 3 seconds ...
thread 3: I'm going to die in 3 seconds ...
thread 3 exit code = -1
分析:
(2)pthread_equal函數(shù)
int pthread_equal(pthread_t t1, pthread_t t2);
作用:比較兩個(gè)線程ID是否相等。
返回值:相等返回非0值,不等返回0值。
由于目前的Linux系統(tǒng)中,線程ID類型為大于0的整數(shù),因此可以用==直接比較是否相等;設(shè)置該函數(shù)是因?yàn)橛锌赡躄inux在未來線程ID pthread_t 類型被修改為結(jié)構(gòu)體實(shí)現(xiàn),因此==就無法直接判斷。
總結(jié)
以上是生活随笔為你收集整理的pthread_cancel、pthread_equal函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 不孕不育有哪些检查
- 下一篇: 线程与进程的控制原语对比
