假设存在这样一个情况:需要N个线程对一个全局的变量进行M次递增操作。首先想到的常常是,使用互斥量。话不多说,看代码:
#include<stdio.h>
#include<pthread.h>
#define mutex_num <span style="white-space:pre"> </span>10
#define test_count 2000000
static volatile int count=0;
pthread_mutex_t mutex;
void *fun(void *arg){
int i=0;
for(i;i<test_count;++i){
pthread_mutex_lock(&mutex);
count++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(){
int i=0;
pthread_t pthread[mutex_num];
pthread_mutex_init(&mutex,NULL);
for(i=0;i<sizeof(pthread)/sizeof(pthread_t);++i){
pthread_create(&pthread[i],NULL,fun,NULL);
}
for(i=0;i<sizeof(pthread)/sizeof(pthread_t);++i){
pthread_join(pthread[i],NULL);
}
printf("[%d]\r\n",count);
return 0;
}
编译、运行程序可以得到正确的结果“count=200000”
至于,为什么count变量要是volatile的,这是避免使用gcc优化选项后直接将M此循环的结果算出,影响了实例代码的显著性。读者可以自己尝试一下:去掉volatile修饰,gcc编译时使用-O2优化,不使用任何同步的情况下(不启用SYNC宏),似乎也能得到正确的结果。