Cancellation Point
http://www.mkssoftware.com/docs/man3/pthread_cancel.3.asp
1、How 结束线程的方式
运行到线程函数结尾、 调用pthread_cancel后遇到了Cancellation Point,线程函数调用 pthread_exit
2、Whether 是否起作用
只有当线程通过pthread_setcancelstate设置Cancellation 为enable,pthread_cancel发出的Cancellation 请求才有作用,默认是enable的
3、when 何时起作用
当通过pthread_setcanceltype设置为asynchronous的,就可以立即线程取消。设置为Deferred,则必须遇到Cancellation Point才能取消,实际上,根据
http://blog.csdn.net/wwyyxx26/article/details/9018473中的Linux 的取消点实现得知,其实最终都是异步的。
4、当开始相应Cancellation 请求后,要执行下面3步(man pthread_cancel)
i. Cancellation clean-up handlers are popped (in the reverse of the order in which they were pushed) and called. (See pthread_cleanup_push(3).)
这里强调了一下顺序,因为我们可以自己通过pthread_cleanup_push来注册clean handler函数,在pop时就会按顺序pop并执行clean函数了
Any cancellation cleanup handlers that have been pushed and not yet popped shall be popped in the reverse order that they were pushed and then executed
先弹出,再执行
ii. Thread-specific data destructors are called, in an unspecified order. (See pthread_key_create(3).)
iii. The thread is terminated. (See pthread_exit(3).)
pthread_exit依靠甩出 ___forced_unwind异常来结束线程,___forced_unwind必须被甩出,不能被catch住
http://stackoverflow.com/questions/11452546/why-does-pthread-exit-throw-something-caught-by-ellipsis
以上3步对于pthread_cancel是异步的。
3、线程里局部变量为一个类,
4、read和那些有Cancellation Point
sleep有Cancellation Point
http://stackoverflow.com/questions/433989/posix-cancellation-points里说明了哪些函数肯定或可能带有Cancellation Point
但是据说由于LinuxThread库与C库结合得不好,因而目前C库函数都不是Cancelation-point,这个有待证实。
注意,没有互斥的相关函数,所以要注意死锁http://blog.csdn.net/wwyyxx26/article/details/9018473
5、结束线程的方式是rethrow?大致流程
6、pthread_exit函数和pthread_cancel区别
pthread_exit在线程函数中调用,来结束线程,他会执行4中提到的i, ii,
7、执行到Cancellation Point,就结束线程了,之后的代码就不会被执行了
因为调用pthread_exit,甩出的 ___forced_unwind异常
比如在一个线程里,使用read阻塞读,那么,pthread_cancel后,read甚至不返回,线程就在这里结束