pthread_cancel 完美退出线程
程序:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
void cleanup(void*)
{
printf("clean\n");
}
void* test_pthread(void*)
{
pthread_cleanup_push(cleanup,NULL); //释放线程内的内存,可以防止内存泄漏
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL); //使能取消点 ,收到取消信号就取消
// pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL); //关闭取消功能
//pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL); //下一个取消点取消
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL); //遇到取消点取消.
while(1)
{
int a = 1;
a = a;
// printf("aaa\n"); //可作取消点 凡有阻塞作有的POSIX C函数都会有取消点, (具体包括哪些,可以查看man 7 pthreads)
pthread_testcancel(); //可作取消点 //如果屏蔽所有的取消点.主程序就会堵在pthread_join里.
// printf("bbb\n");//可作取消点
// printf("ccc\n");//可作取消点
// sleep(5);//可作取消点
// printf("ddd\n");//可作取消点
// pthread_testcancel();//可作取消点
// system("ls");//可作取消点
}
pthread_cleanup_pop(0);
return NULL;
}
int main()
{
pthread_t m_t;
pthread_create(&m_t,0,test_pthread,NULL);
int counter = 0;
while(++counter < 10)
{
printf("counter:%d\n",counter);
if(counter == 3)
{
if(!pthread_cancel(m_t))
{
pthread_join(m_t,NULL); //如果改为pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL); .主程序就会堵在这里.
}
}
sleep(1);
}
}
运行结果:
[user:lib_hdmanage] ./example/main.i386.elf
counter:1
counter:2
counter:3
clean
counter:4
counter:5
counter:6
counter:7
counter:8
counter:9
[user:lib_hdmanage]