1.实现线程信号处理函数
//实现信号处理函数
static void on_func_signal(int sig)
{
printf("%s\n","通过线程信号退出子线程");
pthread_exit(NULL);
}
2.注册线程信号处理函数
signal(SIGQUIT,on_func_signal);//注册线程退出信号
3.创建线程
pthread_t tid;
int x = pthread_create(&tid,
NULL,
thread_func_with_signal,
NULL);
4.向线程发射信号
pthread_kill(tid,SIGQUIT);//主线程向子线程发启退出信号
5.阻塞主线程,直到子线程执行完成
pthread_join(tid,NULL);//阻塞主线程,等待子线程完成退出
6.退出子线程
pthread_exit(NULL)
7.检测指定线程是否存在
//发送0探测线程是否存活
int r = pthread_kill(tid,0);
switch (r) {
case ESRCH:
printf("子线程不存在或者已终止\n");
break;
case EINVAL:
printf("信号非法\n");
break;
default:
break;
}
8.取消正在运行的线程
在子线程的代码中要添加pthread_testcancel();来支持取消操作
支持取消的线程函数实现
void *thread_func_with_cancel(void *arg)
{
printf("子线程thread_func_with_cancel已启动...\n");
int _count =1;
while(true)
{
printf("%d\n",_count);
pthread_testcancel();//支持取消线程执行
_count++;
}
}
创建线程
x = pthread_create(&tid,
NULL,
thread_func_with_cancel,
NULL);
if(x){printf("%s\n","创建线程thread_func_with_cancel失败");}
取消正在执行的线程
void *ret=NULL;
pthread_cancel(tid);//取消线程
pthread_join(tid,&ret);//阻塞主线程,等待子线程取消完成
if(ret==PTHREAD_CANCELED){
printf("成功取消正在运行的子线程thread_func_with_cancel\n");
}
9.通过入栈与出栈清理线程占用资源
清理函数实现
//线程清理函数
void thread_clean(void *arg)
{
printf("thread_clean:%d\n",*((int*)arg));
}
将清理函数入栈:
int n=1;
pthread_cleanup_push(thread_clean,&n);
出栈处理
pthread_cleanup_pop(0);
注: 入栈与出栈是成对出现的,有pthread_cleanup_push开始,就要有pthread_cleanup_pop结束.
当pthread_cleanup_pop(0) 传入的参数为0时不做任何操作