pthread_cancel pthread_testcancel测试
生活随笔
收集整理的這篇文章主要介紹了
pthread_cancel pthread_testcancel测试
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
pthread_cancel用于取消一個(gè)線(xiàn)程,但被取消的線(xiàn)程要有取消點(diǎn),才能被取消。
pthread_testcancel用于設(shè)置取消點(diǎn)
?
/*** Created by fangruibin* 測(cè)試取消線(xiàn)程操作*/#include <stdio.h> #include <pthread.h> #include <unistd.h>pthread_mutex_t m_mutex;//清理函數(shù) void cleanProc(void* arg) {pthread_t tid = pthread_self();printf("thread %lx was canceled\n", tid); }//線(xiàn)程函數(shù) void* threadFunc(void* p) {//設(shè)置可取消pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);//設(shè)置線(xiàn)程清理回調(diào)函數(shù),如果線(xiàn)程是被cancel的,而不是自然結(jié)束的,那么回調(diào)函數(shù)會(huì)被執(zhí)行pthread_cleanup_push(cleanProc, NULL);printf("thread %lx is running..\n", pthread_self());while (1){//設(shè)置cancelation pointpthread_testcancel();sleep(1);pthread_testcancel();}//取消線(xiàn)程清理回調(diào)函數(shù),如果線(xiàn)程是自然結(jié)束的,那么回調(diào)函數(shù)是不會(huì)被執(zhí)行的,需要把它取消掉pthread_cleanup_pop(0);printf("thread %lx exit normally\n", pthread_self());return NULL; }int main() {//初始化線(xiàn)程pthread_t hThread;if (pthread_create(&hThread, NULL, &threadFunc, NULL) != 0){printf("create thread failed\n");return -1;}sleep(5);pthread_cancel(hThread); //取消線(xiàn)程pthread_join(hThread, NULL);sleep(1);printf("main exit\n");return 0; }運(yùn)行結(jié)果如下:
總結(jié)
以上是生活随笔為你收集整理的pthread_cancel pthread_testcancel测试的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 一些常用函数的曲线图及应用简说
- 下一篇: 淘宝API JAVA 乱码