国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

pthread 線程立即取消的兩種方法

2019-11-09 20:34:27
字體:
供稿:網(wǎng)友

1.相關(guān)函數(shù)介紹 a.

int pthread_cancel(pthread_t thread)

發(fā)送終止信號(hào)給thread線程,如果成功則返回0,否則為非0值。發(fā)送成功并不意味著thread會(huì)終止。

b.

int pthread_setcancelstate(int state, int *oldstate)

設(shè)置本線程對(duì)Cancel信號(hào)的反應(yīng),state有兩種值:PTHREAD_CANCEL_ENABLE(缺?。┖蚉THREAD_CANCEL_DISABLE, 分別表示收到信號(hào)后設(shè)為CANCLED狀態(tài)和忽略CANCEL信號(hào)繼續(xù)運(yùn)行;old_state如果不為NULL則存入原來的Cancel狀態(tài)以便恢復(fù)。

c.

int pthread_setcanceltype(int type, int *oldtype)

設(shè)置本線程取消動(dòng)作的執(zhí)行時(shí)機(jī),type由兩種取值:PTHREAD_CANCEL_DEFFERED和PTHREAD_CANCEL_ASYCHRONOUS,僅當(dāng)Cancel狀態(tài)為Enable時(shí)有效,分別表示收到信號(hào)后繼續(xù)運(yùn)行至下一個(gè)取消點(diǎn)再退出和立即執(zhí)行取消動(dòng)作(退出);oldtype如果不為NULL則存入運(yùn)來的取消動(dòng)作類型值。

d.

void pthread_testcancel(void)

是說pthread_testcancel在不包含取消點(diǎn),但是又需要取消點(diǎn)的地方創(chuàng)建一個(gè)取消點(diǎn),以便在一個(gè)沒有包含取消點(diǎn)的執(zhí)行代碼線程中響應(yīng)取消請(qǐng)求. 線程取消功能處于啟用狀態(tài)且取消狀態(tài)設(shè)置為延遲狀態(tài)時(shí),pthread_testcancel()函數(shù)有效。 如果在取消功能處處于禁用狀態(tài)下調(diào)用pthread_testcancel(),則該函數(shù)不起作用。 請(qǐng)務(wù)必僅在線程取消線程操作安全的序列中插入pthread_testcancel()。除通過pthread_testcancel()調(diào)用以編程方式建立的取消點(diǎn)意外,pthread標(biāo)準(zhǔn)還指定了幾個(gè)取消點(diǎn)。測(cè)試退出點(diǎn),就是測(cè)試cancel信號(hào).

e.

int pthread_join(pthread_t thread, void **value_ptr);

thread:等待退出線程的線程號(hào)。 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); /*同步取消,等到下一個(gè)取消點(diǎn)再取消*/ pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); 2.異步取消線程 示例代碼:

#include<stdio.h> #include<stdlib.h> #include <pthread.h> void *thread_fun(void *arg) { int i=1; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); /*同步取消,等到下一個(gè)取消點(diǎn)再取消*/// pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); /*異步取消, 線程接到取消信號(hào)后,立即退出*/ 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
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 沽源县| 确山县| 凤凰县| 东明县| 榆中县| 蒙山县| 图片| 英山县| 浦东新区| 乌苏市| 新野县| 依安县| 南康市| 福鼎市| 集贤县| 平山县| 华亭县| 永胜县| 文成县| 赤壁市| 托克托县| 石泉县| 玉屏| 太和县| 全州县| 遂平县| 万山特区| 巴楚县| 平乡县| 卢氏县| 抚顺市| 平湖市| 呼图壁县| 麦盖提县| 乐昌市| 合川市| 江源县| 鹤峰县| 金华市| 右玉县| 利津县|