首页 > 编程语言 > 详细

线程同步与互斥

时间:2016-04-17 17:59:18      阅读:140      评论:0      收藏:0      [点我收藏+]




  1 #include<stdio.h>
  2 #include<pthread.h>
  3 
  4 static int count = 0;
  5 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
  6 void *pthread(void* arg)
  7 {
  8     int tmp = 0;
  9     int i = 5000;
 10     while(i--)
 11     {
 12         pthread_mutex_lock(&lock);
 13         tmp = count;
 14         printf("this is %d thread,count is %d\n",(int)arg,tmp);
 15         count = tmp +1;
 16         pthread_mutex_unlock(&lock);
 17     }
 18     return (void*)2;
 19 }
 20 int main()
 21 {
 22     pthread_t tid1,tid2;
 23     pthread_create(&tid1,NULL,pthread,(void*)1);
 24     pthread_create(&tid2,NULL,pthread,(void*)2);
 25 
 26     void* status = NULL;
 27     pthread_join(tid1,&status);
 28     pthread_join(tid2,&status);
 29     printf("count is %d\n",count);
 30     return 0;
 31 }
this is 1 thread,count is 5304
this is 1 thread,count is 5305
this is 1 thread,count is 5306
this is 1 thread,count is 5307
this is 1 thread,count is 5308
this is 1 thread,count is 5309
this is 1 thread,count is 5310
this is 1 thread,count is 5311
count is 5312

this is 1 thread,count is 9993
this is 1 thread,count is 9994
this is 1 thread,count is 9995
this is 1 thread,count is 9996
this is 1 thread,count is 9997
this is 1 thread,count is 9998
this is 1 thread,count is 9999
count is 10000


线程同步与互斥

原文:http://fengbaoli.blog.51cto.com/10538178/1764743

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!