Linux系统编程54 线程 - 线程的取消

pthread_cancel() : 取消线程

pthread_setcancelstate() :设置 是否允许取消

pthread_setcanceltype(): 设置取消方式,异步 或者 推迟

pthread_testcancel(): 设置一个取消点

pthread_detach() : 线程分离


前面说到的 pthread_join() 线程收尸,是必须要等线程执行结束才能收尸,而有时候不需要目标线程执行结束 就要结束他,那么怎么收尸呢?

pthread_cancel() + pthread_join()


pthread_cancel() : 取消线程

NAME
       pthread_cancel - send a cancellation request to a thread 给一个线程发送一个取消请求。

SYNOPSIS
       #include <pthread.h>

       int pthread_cancel(pthread_t thread);//取消线程, thread :需要取消的线程ID

       Compile and link with -pthread.

为了防止已经申请的资源不能回收,需要设置取消状态,比如,如果需要取消的线程 刚刚open()了一个文件,此时取消,将会导致错过 close(),造成资源泄露。所以需要设置如下 如下状态:

取消有两种状态:

1 允许取消

1.1 异步取消
1.2 推迟取消,默认是推迟取消, 推迟到 cancel点 再响应

cancel点:POSIX定义的cancel点是指 都是可能引发阻塞的系统调用。

2 不允许取消

int pthread_setcancelstate(int state, int *oldstate); // 设置 是否允许取消

int pthread_setcanceltype(int type, int *oldtype);// 设置取消方式,异步 或者 推迟

NAME
       pthread_setcancelstate, pthread_setcanceltype - set cancelability state and type

SYNOPSIS
       #include <pthread.h>

// 设置 是否允许取消
       int pthread_setcancelstate(int state, int *oldstate); 

// 设置取消方式,异步 或者 推迟
       int pthread_setcanceltype(int type, int *oldtype);

       Compile and link with -pthread.

NAME
pthread_testcancel - 设置一个取消点

应用于 没有任何 可能引发阻塞的系统调用 的功能函数,即线程中,用于设置取消点,以便 取消该线程

SYNOPSIS
       #include <pthread.h>

// 本函数 什么都不做,就是一个取消点
       void pthread_testcancel(void);

       Compile and link with -pthread.

pthread_detach() : 线程分离

一般情况下,对于linux中的资源,我们一直遵循 :谁打开,谁关闭。谁申请,谁释放 这回原则。但是也有特殊情况,假如 创建出某个线程 就不再关心它的生死存亡,就可以分离出去,即
pthread_detach()。

注意 已经 pthread_detach()分离的线程,是不能 进行 pthread_join() 收尸的

NAME
       pthread_detach - detach a thread 分离一个线程

SYNOPSIS
       #include <pthread.h>

       int pthread_detach(pthread_t thread);

       Compile and link with -pthread.

猜你喜欢

转载自blog.csdn.net/LinuxArmbiggod/article/details/114232088