pthread_cancel
用于线程的退出
在线程内部退出,使用pthread_exit(),这个特点就是不会释放一些共享内存(e.g., mutexes,
condition variables, semaphores, and file descriptors)
只有在进程exit()之后才会释放
也可以使用pthread_cancel(tid)对线程定向cancel
pthread_cancel 取决于 cancelability state and type.
默认是enable,deferred
state: enable/disable pthread_setcancelstate()可更改
type : asynchronous/ deferred pthread_setcanceltype()可更改
如果disable cancel,则直到线程设置为enable,才能够cancel
如果能够cancel,检查type,如果是asychromous,则立即cancel
deferred,等待到cancellation_point(该线程调用某个函数)才cancel
cancellation_point函数,一般都是一些对文件描述符的操作(比如read)
一个线程cancel的流程:
1. cancellation clean-up handlers从栈里面pop并调用 通过 pthread_cleanup_push()入栈的handler
2. tls数据的destructor被调用 pthread_key_create()指定的void(*destructor)(void*)
3. terminate 调用pthread_exit()
当线程cancel后,若将线程加入pthread_join,会收到PTHREAD_CANCELED 作为线程退出状态,join是唯一的方式得知线程退出完成