pthread_cancel()取消线程

1680阅读 0评论2014-10-17 vibe26
分类:C/C++

代码下载a.zip

点击(此处)折叠或打开

  1. #include<pthread.h>
  2. int pthread_cancel(pthread_t tid)
线程取消属性没有包含在pthread_attr_t结构中,所以调用pthread_cancel(pthread_t tid)不需要初始化pthread_attr_t结构;

点击(此处)折叠或打开

  1. #include<pthread.h>
  2. int pthread_setcanceltypeint type,int *oldtype)
当设置type为PTHREAD_CANCEL_ASYNCHRONOUS异步取消时,线程可以在不遇到取消点时就可以取消,就是说一被cancel就停止运行
若type设置为PTHREAD_CANCEL_DEFERRED延迟取消时,线程必须要等到取消点才能取消。

关于pthread_setcancelstate就不多说了,在书上331页有讲解。
一个取消的例子

点击(此处)折叠或打开

  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include<unistd.h>

  4. pthread_t tid1,tid2;

  5. void *fn_1(void *arg)
  6. {
  7.     pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
  8.     printf("Thread 1 is running...\n");
  9.     while(1)
  10.     {
  11.         printf("running...\n");
  12.         sleep(1);
  13.     }
  14.     printf("I was cancelled by other thread\n");
  15.     pthread_exit((void*)1);
  16. }

  17. void *fn_2(void*arg)
  18. {
  19.     printf("Thread 2 is running...I will cancel thread 1 after 5 seconds\n");
  20.     sleep(5);
  21.     pthread_cancel(tid1);
  22.     pthread_exit((void*)2);
  23. }

  24. int main()
  25. {
  26.     pthread_create(&tid1,NULL,fn_1,NULL);    
  27.     pthread_create(&tid2,NULL,fn_2,NULL);
  28.     pthread_join(tid1,NULL);    
  29.     pthread_join(tid2,NULL);    
  30.     return 0;
  31. }
运行结果:

点击(此处)折叠或打开

  1. [vibe@localhost code]$ ./a
  2. Thread 1 is running...
  3. running...
  4. Thread 2 is running...I will cancel thread 1 after 5 seconds
  5. running...
  6. running...
  7. running...
  8. running...




上一篇:error.h
下一篇:初始化一个守护进程