1、描述;
两个线程同时访问同一个全局变量counter的时候需要加互斥锁
2、关键字
互斥锁:
- 互斥锁
互斥锁是用来防止多个线程同时访问共享资源对象的机制,在同一时间只有一个线程可以拥有一个特定的锁对象,其他线程如果尝试获取锁会阻塞直到锁资源被释放或直接返回失败。
3、思路
1 全局变量的时候初始化一个全局变量的锁,
2 在构造子线程的回调函数中把处理这个全局变量的代码段开始时:获取这个锁对象。代码段结束,解锁(释放这个锁对象)。
6、code
#include <pthread.h>
#include <iostream>
using namespace std;
#define NLOOP 10
int counter=0;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; // 初始化锁
void *doit(void *);
int main(int argc,char **argv)
{
pthread_t tidA,tidB;
pthread_create(&tidA,NULL,&doit,NULL);
pthread_create(&tidB,NULL,&doit,NULL);
pthread_join(tidA,NULL);//join函数是main线程要等待tidA和tidB的线程结束后再退出
pthread_join(tidB,NULL);
return 0;
}
void * doit(void *vptr){
int i,val;
//pthread_mutex_lock(&counter_mutex);//这里需要把counter的操作都锁起来,否则在2个线程切换的时候会出错。
for(i=0;i<NLOOP;i++){
pthread_mutex_lock(&mtx);//这里需要把counter的操作都锁起来,否则在2个线程切换的时候会出错。
val = counter;
cout << "thread id=" << pthread_self()<<" val = ";
cout << val+1 << endl;
counter = val +1;
pthread_mutex_unlock(&mtx);
}
//pthread_mutex_unlock(&counter_mutex);
return (NULL);
}
编译:
需要加-pthread:
g++ m_pthread.cpp -pthread
互斥锁加在内部,不一定两个线程平均分20次,每个线程10次,
加外边就行了。
效果:
thread id=140498213148416 val = 1
thread id=140498213148416 val = 2
thread id=140498213148416 val = 3
thread id=140498213148416 val = 4
thread id=140498213148416 val = 5
thread id=140498213148416 val = 6
thread id=140498213148416 val = 7
thread id=140498213148416 val = 8
thread id=140498213148416 val = 9
thread id=140498204755712 val = 10
thread id=140498204755712 val = 11
thread id=140498204755712 val = 12
thread id=140498204755712 val = 13
thread id=140498204755712 val = 14
thread id=140498204755712 val = 15
thread id=140498204755712 val = 16
thread id=140498204755712 val = 17
thread id=140498204755712 val = 18
thread id=140498204755712 val = 19
thread id=140498213148416 val = 20