理解CAS与__sync_bool_compare_and_swap

972 篇文章 328 订阅
148 篇文章 34 订阅

      CAS是compare and swap,   简单来说就是,在写入新值之前, 读出旧值, 当且仅当旧值与存储中的当前值一致时,才把新值写入存储。__sync_bool_compare_and_swap是可供程序员调用的接口, 为什么需要CAS呢? 一起来看下:

       让10个线程执行加法操作, 看看最简单的版本:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

int sum = 0;

void* adder(void *p)
{
    for(int i = 0; i < 1000000; i++)  // 百万次
    {
        sum++;
    }

    return NULL;
}

int main()
{
    pthread_t threads[10];

    for(int i = 0; i < 10; i++)
    {
        pthread_create(&threads[i], NULL, adder, NULL);
    }
	
    for(int i = 0; i < 10; i++)
    {
        pthread_join(threads[i],NULL);
    }

	printf("sum is %d\n", sum);
}

          运行了一下, 发现每次结果不一样, 并不是10000000, 原因很简单, 多线程没有同步。 结果也说明,++不是原子操作。

  

          怎么办? 加锁, 这是无疑的, 如下:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

int sum = 0;
pthread_mutex_t mutex;

void* adder(void *p)
{
    for(int i = 0; i < 1000000; i++)  // 百万次
    {
    	pthread_mutex_lock(&mutex);
        sum++;
		pthread_mutex_unlock(&mutex);
    }

    return NULL;
}

int main()
{
    pthread_t threads[10];
    pthread_mutex_init(&mutex, NULL);

    for(int i = 0; i < 10; i++)
    {
        pthread_create(&threads[i], NULL, adder, NULL);
    }
	
    for(int i = 0; i < 10; i++)
    {
        pthread_join(threads[i],NULL);
    }

	printf("sum is %d\n", sum);
}

        多次运行发现, 结果总是10000000, 加锁了, 安全。 

        但是, 问题来了, 加锁效率如何, 多进程,多机器修改怎么办?  比如典型的银行卡扣款场景。 且看CAS机制:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

int sum = 0;

void* adder(void *p)
{
    int old = sum;
    for(int i = 0; i < 1000000; i++)  // 百万次
    {
        while(!__sync_bool_compare_and_swap(&sum, old, old + 1))  // 如果old等于sum, 就把old+1写入sum
        {
           old = sum; // 更新old
        }
    }

    return NULL;
}

int main()
{
    pthread_t threads[10];
    for(int i = 0;i < 10; i++)
    {
        pthread_create(&threads[i], NULL, adder, NULL);
    }
	
    for(int i = 0; i < 10; i++)
    {
        pthread_join(threads[i], NULL);
    }

    printf("sum is %d\n",sum);
}

          结果是10000000, 可以好好理解下。 有兴趣的同学, 可以测测上述程序的效率。

          对了, 最后一个程序的编译方法为:g++ test.cpp  -lpthread -march=nocona -mtune=generic

 

         不多说。

 

 

  • 12
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值