linux多线程编程---线程同步之互斥锁

假设存在这样一个情况:需要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宏),似乎也能得到正确的结果。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值