linux线程中如何控制子线程退出
程序员文章站
2024-03-15 17:33:06
...
- List item
linux线程中如何控制子线程退出
一.相关接口介绍
1.线程的创建-pthread_create
使用man 3 查询函数使用
int pthread_create(pthread_t *thread, //线程id
const pthread_attr_t *attr, //线程属性,一般为空
void *(*start_routine) (void *), //线程处理函数
void *arg);//线程参数
2.线程取消接口-pthread_cancel
int pthread_cancel(pthread_t thread);
3.线程取消函数,只是给指定线程发送取消的信号,即使发送成功,也不代表子线程会退出,子线程本身需要设置如下
pthread_setcancelstate–是能线程取消功能
pthread_setcanceltype–设置线程取消类型
int pthread_setcancelstate(int state, int *oldstate);
int pthread_setcanceltype(int type, int *oldtype);
state 取值:
PTHREAD_CANCEL_ENABLE //收到canael信号,取消当前线程
The thread is cancelable. This is the default cancelability state in all new threads, including the initial thread.
The thread's cancelability type determines when a cancelable thread will respond to a cancellation request.
PTHREAD_CANCEL_DISABLE//可以理解为忽略cancel信号
The thread is not cancelable. If a cancellation request is received, it is blocked until cancelability is enabled.
type取值:
PTHREAD_CANCEL_DEFERRED //延迟取消,下一个取消点取消,建立取消点函数pthread_testcancel();
A cancellation request is deferred until the thread next calls a function that is a cancellation point (see pthreads(7)). This is the default cancelability type in all new threads, including the initial thread.
PTHREAD_CANCEL_ASYNCHRONOUS//立即取消
The thread can be canceled at any time. (Typically, it will be canceled immediately upon receiving a cancellation request, but the system doesn't guarantee this.)
4.pthread_join --主线程阻塞,等待某个子线程退出
5.pthread_exit --线程退出接口
二. 实例
1.异步线程控制子线程退出
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_t my_thread;
void * pthread_fun(void * arg)
{
//收到cancel信号,取消此线程
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
//立即取消此线程
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
int recvmsg = *(int*)arg;
while(1)
{
printf("this msg %d \n",recvmsg);
sleep(1);
}
}
int main(int argc, const char *argv[])
{
int ret = 0;
int msg = 888;
int i = 0;
void * canel_ret;
ret = pthread_create(&my_thread,NULL,pthread_fun,&msg);
if(ret != 0)
{
printf("pthread create fail \n");
return ret;
}
for(i=0;i<10;i++)
{
printf("main i:%d \n",i);
if(i == 9)
{
pthread_cancel(my_thread);
}
sleep(1);
}
//等待指定线程退出回收资源
pthread_join(my_thread,&canel_ret);
printf("cancel ret %d \n",(int)canel_ret);
return 0;
}
测试结果,主线程运行10s 后 退出
2.同步退出方法
主线程发送cancel信号后,子线程不会立即退出,需要运行到取消点,退出,如果线程中没有取消点函数,取消点由我们去设置。
sleep函数其实可以把它当做一个取消点的,或者使用pthread_testcancel自己设置。
注意:被取消的线程,退出值,定义在Linux的pthread库中常数PTHREAD_CANCELED的值是-1。
取消点函数,posix有定义取消点函数。