Chinaunix首页 | 论坛 | 博客
  • 博客访问: 157653
  • 博文数量: 76
  • 博客积分: 1513
  • 博客等级: 上尉
  • 技术积分: 755
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-25 15:15
文章分类

全部博文(76)

文章存档

2012年(2)

2011年(74)

我的朋友

分类: C/C++

2011-11-25 21:05:16

  1. #include<iostream>

  2. #include<pthread.h>

  3. #include<stdint.h>

  4. using namespace std;

  5.  

  6. struct thread_param

  7. {

  8. int8_t info;

  9. int32_t num;

  10. };

  11.  

  12. void* thread_fun(void* argc)

  13. {

  14. struct thread_param* p;

  15. p=(thread_param*)argc;

  16. int i;

  17. for(i=0;i<p->num;i++)

  18. {

  19. cout<<i<<":"<<p->info<<"Thread ID:"<<pthread_self()<<endl;

  20. sleep(1);

  21. }

  22.  

  23. return NULL;

  24. }

  25.  

  26. int main(void)

  27. {

  28. pthread_t id1,id2;

  29. struct thread_param info1,info2;

  30. int ret;

  31. info1.info='s';

  32. info1.num=20;

  33.  

  34. pthread_attr_t attr_obj1;

  35. pthread_attr_t attr_obj2;

  36. pthread_attr_init(&attr_obj1);

  37. pthread_attr_init(&attr_obj2);

  38.  

  39.  

  40.  

  41. ret=pthread_create(&id1,&attr_obj1,thread_fun,&info1);

  42. if(ret!=0)

  43. {

  44. cout<<"cannot create new thread\n";

  45. return 1;

  46. }

  47.  

  48. info2.info='t';

  49. info2.num=20;

  50. ret=pthread_create(&id2,&attr_obj1,thread_fun,&info2);

  51. if(ret!=0)

  52. {

  53. cout<<"cannot create new thread\n";

  54. return 1;

  55. }

  56.  

  57. if(pthread_join(id1,NULL)!=0)

  58. {

  59. cout<<"call pthread_join function failed!\n";

  60. return 1;

  61. }

  62. if(pthread_join(id2,NULL)!=0)

  63. {

  64. cout<<"call pthread_join function failed!\n";

  65. return 1;

  66. }

  67. return 0;

  68. }

运行结果:

0:sThread ID:3086392208

0:tThread ID:3075902352

1:sThread ID:3086392208

1:tThread ID:3075902352

2:sThread ID:3086392208

2:tThread ID:3075902352

3:sThread ID:3086392208

3:tThread ID:3075902352

4:sThread ID:3086392208

4:tThread ID:3075902352

5:sThread ID:3086392208

5:tThread ID:3075902352

6:sThread ID:3086392208

6:tThread ID:3075902352

7:sThread ID:3086392208

7:tThread ID:3075902352

8:sThread ID:3086392208

8:tThread ID:3075902352

9:sThread ID:3086392208

9:tThread ID:3075902352

10:sThread ID:3086392208

10:tThread ID:3075902352

11:sThread ID:3086392208

11:tThread ID:3075902352

12:sThread ID:3086392208

12:tThread ID:3075902352

13:sThread ID:3086392208

13:tThread ID:3075902352

14:sThread ID:3086392208

14:tThread ID:3075902352

15:sThread ID:3086392208

15:tThread ID:3075902352

16:sThread ID:3086392208

16:tThread ID:3075902352

17:sThread ID:3086392208

17:tThread ID:3075902352

18:sThread ID:3086392208

18:tThread ID:3075902352

19:sThread ID:3086392208

19:tThread ID:3075902352


可以发现线程之间是并发运行的
阅读(866) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~