《unix高级环境编程》线程控制——线程取消选项

梦里梦外; 2022-08-14 00:42 330阅读 0赞

线程的取消选项有两种:可取消状态、可取消类型。这两个属性影响 pthread_cancel 函数的工作。

可取消状态

可取消状态属性有两种状态,分别为 PTHREAD_CANCEL_ENABLE (默认) 和 PTHREAD_CANCEL_DISABLE。线程可以通过以下函数修改可取消状态:

  1. /* 线程取消选项 */
  2. /*
  3. * 函数功能:修改可取消状态属性;
  4. * 返回值:若成功则返回0,否则返回错误编码;
  5. * 函数原型:
  6. */
  7. #include <pthread.h>
  8. int pthread_setcancelstate(int state, int *oldstate);
  9. /*
  10. * 说明:
  11. * 该函数把可取消状态设置为state,把旧的可取消状态存放在oldstate所指的内存单元中;
  12. */
  13. /*
  14. * 函数功能:添加线程的取消点;
  15. * 无返回值;
  16. * 函数原型:
  17. */
  18. #include <pthread.h>
  19. void pthread_testcancel(void);
  20. /*
  21. * 说明:
  22. * 调用该函数时,若有某个取消请求处于未决状态,而且取消并没有置为无效,
  23. * 则线程就会被取消;但是若取消置为无效,则该函数调用没有任何效果;
  24. */

可取消类型

可取消类型属性有两种类型,分别为 PTHREAD_CANCEL_DEFERRED (延时取消) 和 PTHREAD_CANCEL_ASYNCHRONOUS(异步取消)。线程可以通过以下函数修改可取消类型:

  1. /*
  2. * 函数功能:修改取消类型;
  3. * 返回值:若成功则返回0,否则返回错误编码;
  4. * 函数原型:
  5. */
  6. #include <pthread.h>
  7. int pthread_setcanceltype(int type, int *oldtype);

测试程序:

  1. #include "apue.h"
  2. #include <pthread.h>
  3. static void *fun1(void *arg);
  4. static void *fun2(void *arg);
  5. pthread_t tid1, tid2;
  6. int err;
  7. int main(void)
  8. {
  9. err = pthread_create(&tid1, NULL, fun1, NULL);
  10. if(err != 0)
  11. err_quit("can't create thread: %s\n", strerror(err));
  12. err = pthread_create(&tid2, NULL, fun2, NULL);
  13. if(err != 0)
  14. err_quit("can't create thread: %s\n", strerror(err));
  15. err = pthread_detach(tid1);
  16. if(err != 0)
  17. err_quit("detach error: %s\n", strerror(err));
  18. err = pthread_detach(tid2);
  19. if(err != 0)
  20. err_quit("detach error: %s\n", strerror(err));
  21. exit(0);
  22. }
  23. static void *fun1(void *arg)
  24. {
  25. err = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  26. if(err != 0)
  27. err_quit("set state error: %s\n", strerror(err));
  28. printf("thread 1 starting...\n");
  29. sleep(15);
  30. printf("thread 1 returnting...\n");
  31. err = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  32. if(err != 0)
  33. err_quit("set state error: %s\n", strerror(err));
  34. printf("thread 1.2 starting...\n");
  35. pthread_testcancel();
  36. printf("thread 1.2 returnting...\n");
  37. pthread_exit((void*)0);
  38. }
  39. static void *fun2(void *arg)
  40. {
  41. printf("thread 2 starting...\n");
  42. err = pthread_cancel(tid1);
  43. if(err != 0)
  44. err_quit("can't cancel thread 1: %s\n", strerror(err));
  45. printf("thread 2 returnting...\n");
  46. pthread_exit((void*)0);
  47. }

参考资料:

《UNIX高级环境编程》

发表评论

表情:
评论列表 (有 0 条评论,330人围观)

还没有评论,来说两句吧...

相关阅读