pthread_cancel

590阅读 0评论2015-10-18 乐天226
分类:LINUX


点击(此处)折叠或打开

  1. #include "stdio.h"
  2. #include "string.h"
  3. #include "pthread.h"
  4. #include "unistd.h"
  5. #include "stdlib.h"


  6. void * thr_fn1(void *arg)
  7. {
  8.     printf("thread 1 returning\n");
  9.     return (void *)1;
  10. }

  11. void * thr_fn2(void *arg)
  12. {
  13.     printf("thread 2 returning\n");
  14.     return (void *)2;
  15. }

  16. void * thr_fn3(void *arg)
  17. {
  18.     while(1)
  19.     {
  20.      printf("thread 3 writing\n");
  21.         sleep(1);
  22.     }
  23. }

  24. int main(void)
  25. {
  26.     pthread_t tid = 0;
  27.     void *tret = NULL;
  28.     
  29.     pthread_create(&tid,NULL,thr_fn1,NULL);
  30.     pthread_join(tid,&tret);
  31.     printf("thread 1 exit code %d\n",tret);
  32.     
  33.     pthread_create(&tid,NULL,thr_fn2,NULL);
  34.     pthread_join(tid,&tret);
  35.     printf("thread 2 exit code %d\n",tret);    
  36.     
  37.     pthread_create(&tid,NULL,thr_fn3,NULL);
  38.     sleep(3);
  39.     pthread_cancel(tid);/*强制结束thr_fn3*/
  40.     pthread_join(tid,&tret);
  41.     printf("thread 2 exit code %d\n",tret);

  42.     return 0;    
  43. }
编    译:gcc -o pthread_create pthread_create.c -l pthread
运行结果:
thread 1 returning
thread 1 exit code 1
thread 2 returning
thread 2 exit code 2
thread 3 writing
thread 3 writing
thread 3 writing
thread 2 exit code -1

上一篇:pthread_create
下一篇:pthread_mutex