c++多线程操作全局变量的锁的问题

  2个线程同时改变一个全局变量counter的时候,需要加一个锁。

 

  2 #include <pthread.h>
  3 #include <iostream>
  4
  5 using namespace std;
  6 #define NLOOP 5000
  7 int counter=0;
  8 pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
  9
 10 void *doit(void *);
 11 int main(int argc,char **argv)
 12 {
 13         pthread_t tidA,tidB;
 14         pthread_create(&tidA,NULL,&doit,NULL);
 15         pthread_create(&tidB,NULL,&doit,NULL);
 16
 17         pthread_join(tidA,NULL);//join函数是main线程要等待tidA和tidB的线程结束后再退出
 18         pthread_join(tidB,NULL);
 19
 20         exit(0);
 21 }
 22
 23 void * doit(void *vptr){
 24         int i,val;
 25         for(i=0;i<NLOOP;i++){
 26                 pthread_mutex_lock(&counter_mutex);//这里需要把counter的操作都锁起来,否则在2个线程切换的时候会出错。
 27                 val = counter;
 28                 cout << pthread_self()<<":";
 29                 cout << val+1 << endl;
 30                 counter = val +1;
 31                 pthread_mutex_unlock(&counter_mutex);
 32         }
 33         return (NULL);
 34 }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值