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

全部博文(76)

文章存档

2012年(2)

2011年(74)

我的朋友

分类: C/C++

2011-11-25 21:04:09

  1. #include<pthread.h>

  2. #include<iostream>

  3. #include<stdint.h>

  4. using namespace std;

  5.  

  6. int32_t var;

  7. pthread_mutex_t locker=PTHREAD_MUTEX_INITIALIZER;

  8.  

  9. void* thread_fun(void*)

  10. {

  11. for(int32_t i=0;i<4;i++)

  12. {

  13. pthread_mutex_lock(&locker);

  14. cout<<"in thread......"<<i<<endl;

  15. var++;

  16. cout<<"var:"<<var<<endl;

  17. pthread_mutex_unlock(&locker);

  18. sleep(1);

  19.  

  20. }

  21. return NULL;

  22. }

  23.  

  24. int32_t main()

  25. {

  26. pthread_t thread_id;

  27. if(pthread_create(&thread_id,NULL,thread_fun,NULL)!=0)

  28. {

  29. cout<<"cannot creat new thread"<<endl;

  30. return 1;

  31. }

  32. for(int32_t i=0;i<4;i++)

  33. {

  34. pthread_mutex_lock(&locker);

  35. cout<<"in main thread......"<<i<<endl;

  36. var++;

  37. cout<<"var:"<<var<<endl;

  38. pthread_mutex_unlock(&locker);

  39. sleep(1);

  40. }

  41. if(pthread_join(thread_id,NULL))

  42. {

  43. cout<<"cannot joint thread"<<endl;

  44. return 1;

  45. }

  46. //将主线程加锁,用户输入“123”方能解锁、然后主线程关闭。

  47. pthread_mutex_lock(&locker);

  48. while(true)

  49. {

  50. int a;

  51. cout<<"input the number:"<<endl;

  52. cin>>a;

  53. if(a==123)

  54. {

  55. pthread_mutex_unlock(&locker);

  56. break;

  57. }

  58.  

  59. }

  60. cout<<"\t\tvar:"<<var<<endl;

  61. return 0;

  62. }

输出:

in main thread......0

var:1

in thread......0

var:2

in main thread......1

var:3

in thread......1

var:4

in main thread......2

var:5

in thread......2

var:6

in main thread......3

var:7

in thread......3

var:8

input the number:

124

input the number:

26

input the number:

123

var:8

阅读(650) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~