Chinaunix首页 | 论坛 | 博客
  • 博客访问: 61168
  • 博文数量: 96
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 852
  • 用 户 组: 普通用户
  • 注册时间: 2014-07-13 20:47
个人简介

扎斯特都恩特

文章分类

全部博文(96)

文章存档

2018年(1)

2017年(2)

2016年(82)

2015年(11)

我的朋友

分类: LINUX

2015-10-18 18:45:38


点击(此处)折叠或打开

  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

阅读(531) | 评论(0) | 转发(0) |
0

上一篇:pthread_create

下一篇:pthread_mutex

给主人留下些什么吧!~~