一、线程取消相关函数
1pthread_cancel().线程取消函数
成功返回0,失败返回错误码。
2.pthread_setcancelstate().设置线程取消状态
成功返回0,失败返回错误码。
该函数第一个参数,有两种情况(响应和不响应取消函数),第二个参数就旧状态,一般为空。
3.pthread_setcanceltype().设置取消类型
在可取消的状态下 ,又分为立即取消和延时取消。
成功返回0,失败返回错误码。
该函数第一个参数:有两个种状态立即取消和延时取消,第二个参数就旧状态,一般为空
扩展:延时取消涉及到一个取消点(cancel point),在书册中man pthreads
二:代码
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<pthread.h> void* thread_fun(void * arg) { printf("i am new thread ...\n"); //pthread_setcancelstate(state, *oldstate); int cancel_state; cancel_state = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); if(cancel_state != 0) { printf("pthread_setpthreadstate is failed ...\n"); return (void*)0; } //printf("i am new thread ...\n"); sleep(3); printf("about to cancel.\n"); //pthread_setcancelstate(state, *oldstate); cancel_state = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL); if(cancel_state != 0) { printf("pthread_setcancelstate is failed ...\n"); return (void*)0; } //pthread_setcanceltype(state, *oldstate); int cancel_type; cancel_type = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL); if (cancel_type != 0) { printf("pthread_t"); return (void*)0; } //set cancelpoint: printf(); printf("i am first cancelpoint...\n"); printf("i am second cancelpoint ...\n"); return (void*)20; } int main(int argc , char ** argv) { pthread_t tid; int err ; void *retval; //creat new thread err = pthread_create(&tid , NULL , thread_fun, NULL); if(err != 0) { printf("pthread create is failed..\n"); return 0; } printf("i am main thread...\n"); sleep(1); //pthread_cancel(pthread_t tid); int cancel_val ; cancel_val = pthread_cancel(tid); if(cancel_val != 0) { printf("pthread cancel is failed ...\n"); return 0; } // pthread_join(pthread_t tid ,void**retval); int join_val; join_val = pthread_join(tid,&retval); if(join_val != 0) { printf("pthread join is failed ...\n"); return 0; } //printf(" new thread exit coid"); printf("the new thread exit code is %d\n",(int *)retval); return 0; }
运行程序