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 }