12.7 Cancal选项


还有两个线程属性并没有包含在pthread_attr_t结构中,它们是cancelability state以及cancelability type。这两个属性影响了线程对于函数调用pthread_cancel的相应行为。(11.5节)
cancelability state属性可以取值PTHREAD_CANCEL_ENABLE或者是PTHREAD_CANCEL_DISABLE,线程可以调用函数pthread_setcancelstate修改其cancelbility state.

  1. #include <pthread.h>
  2. int pthread_setcancelstate(int state, int *oldstate);
  3. Return: 0 if OK, error number on failure.

该函数是一个原子操作,能够将当前的cancelability state设置为state,并将之前的cancelability state存储在oldstate指针所指位置。
在11.5节中提到,函数pthread_cancel并不会等待线程终止,在默认情况下,线程将会在canellation请求发出以后继续运行,直到线程到达一个cancellation point,所谓的cancellation point 是指会检查线程线程时候已经被取消了的地方,如果线程被取消了,那么就会相应请求,POSIX.1保证了cancellation point将会在线程调用如下函数的时候出现;

线程启动的时候,其cancelability state的默认值是PTHREAD_CANCEL_ENABLE,当state被设置成PTHREAD_CANCEL_DISABLE的时候,对于函数pthread_cancel的调用并不会终止线程,取而代之的是,cancellation请求将会一直处于挂起状态,当线程状态再一次被使能的时候,线程就会在接下来的cancellation point响应挂起状态的cancellation请求。
除了图12.14列出的函数之外,POSIX.1还指出,图12.15中列出的函数是可选的cancellation points.



如果你的应用程序在很长一段时间内都没有调用图12.14以及图12.15中的函数的话,你可以调用函数pthread_testcancel来增加你自己的cancellation point到程序中。

  1. #include <pthread.h>
  2. void pthread_testcancel(void);

当你调用函数pthread_testcancel的时候,如果cancellation请求处于挂起状态,并且如果cancellation没有被不使能的话,线程就会被取消,当取消不使能的时候,函数pthread_testcancel并不会由任何影响。
我们已经描述的默认的cancellation type是deferred cancellation(延期取消),即是说,在调用函数pthread_cancel之后,实际的取消动作在线程到达cancellation point之前并不会出现,我们可以使用函数pthread_setcanceltype来修改取消类型.

  1. #include <pthread.h>
  2. int pthread_setcanceltype(int type, int *oldtype);
  3. Returns: 0 if OK, error number on failure.

可以设置的类型由两种,PTHREAD_CANCEL_DEFERRED或者是PTHREAD_CANCEL_ASYNCHRONOUS,并且返回之前的类型到指针所指的内存中。
异步取消与延期取消不同,异步取消可以在任意时间点取消,而不必等到cancellation point.





posted @ 2016-07-02 19:51  U201013687  阅读(477)  评论(0编辑  收藏  举报