码迷,mamicode.com
首页 > 编程语言 > 详细

码海拾遗:Linux多线程mutex锁

时间:2017-10-15 21:21:32      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:span   +=   int   reason   class   join   errno   pre   err   

  多线程计数,每个线程累加10个数。

  实现:

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <errno.h>
  5 #include <pthread.h>
  6 
  7 pthread_mutex_t num_lock;
  8 
  9 int num = 0;
 10 int sum = 0;
 11 
 12 void* foo1()
 13 {
 14 #if 1
 15     pthread_mutex_lock(&num_lock);
 16     for(int i = 0;i<10;++i)
 17     {
 18         num += 1;
 19         sum += num;
 20         printf("thread 1,num = %d,sum = %d\n",num,sum);
 21         usleep(10);
 22     }
 23     pthread_mutex_unlock(&num_lock);
 24 #else
 25     for(int i = 0;i<10;++i)
 26     {
 27         num += 1;
 28         sum += num;
 29         printf("thread 1,num = %d,sum = %d\n",num,sum);
 30         usleep(10);
 31     }
 32 #endif
 33     return NULL;
 34 }
 35 
 36 void* foo2()
 37 {
 38 #if 1
 39     pthread_mutex_lock(&num_lock);
 40     for(int i = 0;i<10;++i)
 41     {
 42         num += 1;
 43         sum += num;
 44         printf("thread 2,num = %d,sum = %d\n",num,sum);
 45         usleep(10);
 46     }
 47     pthread_mutex_unlock(&num_lock);
 48 #else
 49     for(int i = 0;i<10;++i)
 50     {
 51         num += 1;
 52         sum += num;
 53         printf("thread 2,num = %d,sum = %d\n",num,sum);
 54         usleep(10);
 55     }
 56 #endif
 57     return NULL;
 58 }
 59 
 60 int main(int argc,char* argv[])
 61 {
 62     pthread_t tid1,tid2;
 63     int err;
 64 
 65     pthread_mutex_init(&num_lock,NULL);
 66 
 67     err = pthread_create(&tid1,NULL,foo1,NULL);
 68     if(err != 0)
 69     {
 70         printf("error code:%d,reason:%s\n",err,strerror(err));
 71         return -1;
 72     }
 73 
 74     err = pthread_create(&tid2,NULL,foo2,NULL);
 75     if(err != 0)
 76     {
 77         printf("error code:%d,reason:%s\n",err,strerror(err));
 78         return -1;
 79     }
 80 
 81     //for(int i = 0;i<10;++i)
 82     //    printf("main thread, num = %d\n",num++);
 83 
 84     err = pthread_join(tid1,NULL);
 85     if(err != 0)
 86     {
 87         printf("error code:%d,reason:%s\n",err,strerror(err));
 88         return -1;
 89     }
 90     err = pthread_join(tid2,NULL);
 91     if(err != 0)
 92     {
 93         printf("error code:%d,reason:%s\n",err,strerror(err));
 94         return -1;
 95     }
 96 
 97     pthread_mutex_destroy(&num_lock);
 98 
 99     return 0;
100 }

 

码海拾遗:Linux多线程mutex锁

标签:span   +=   int   reason   class   join   errno   pre   err   

原文地址:http://www.cnblogs.com/lianshuiwuyi/p/7673807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!