多线程中的count++问题---互斥、自旋、原子操作

46 篇文章 1 订阅

1.互斥mutex:阻止其他线程的进入,其他线程会挂起

2.自旋锁:一直等,(while(1))线程不会切换,操作时间比较短,简单的适合自旋锁

3.原子操作:三条指令合在一起

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#define THREAD_NUM 10
pthread_mutex_t mutex;
pthread_spinlock_t spinlock;
int inc(int*value, int add)
{
	int old;
	__asm__ volatile(
	"lock; xaddl %2, %1;"
	:"=a"(old)
	:"m" (*value), "a" (add)
	:"cc", "memory"
	);
	return old;
}
void* thread_proc(void* arg){
	int *count = (int*)arg;
	int i = 0;
	while(i++ < 100000){
#if 0
		(*count)++;
#elif 0
	pthread_mutex_lock(&mutex);
	(*count)++;
	pthread_mutex_unlock(&mutex);
#elif 0
	pthread_spin_lock(&spinlock);
	(*count)++;
	pthread_spin_unlock(&spinlock);
#elif 1
	inc(count,1);
#endif 
         usleep(1);	
	}
	
}
int main(){
int i= 0;
pthread_t thread_id[THREAD_NUM];
pthread_mutex_init(&mutex,NULL);
pthread_spin_init(&spinlock, PTHREAD_PROCESS_SHARED);
int count = 0;
for(i = 0; i < THREAD_NUM; i++){
	pthread_create(thread_id+i,NULL,thread_proc,&count);
 }
for(i = 0; i < 100; i++)
{
	sleep(1);
	printf("count-->%d\n",count);
}
for(i = 0; i < THREAD_NUM; i++)
{
	pthread_join(thread_id[i], NULL);
}
return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值