理解CAS与__sync_bool_compare_and_swap

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

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


 
 
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. int sum = 0;
  5. void* adder(void *p)
  6. {
  7. for( int i = 0; i < 1000000; i++) // 百万次
  8. {
  9. sum++;
  10. }
  11. return NULL;
  12. }
  13. int main()
  14. {
  15. pthread_t threads[ 10];
  16. for( int i = 0; i < 10; i++)
  17. {
  18. pthread_create(&threads[i], NULL, adder, NULL);
  19. }
  20. for( int i = 0; i < 10; i++)
  21. {
  22. pthread_join(threads[i], NULL);
  23. }
  24. printf( "sum is %d\n", sum);
  25. }

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

  

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


 
 
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. int sum = 0;
  5. pthread_mutex_t mutex;
  6. void* adder(void *p)
  7. {
  8. for( int i = 0; i < 1000000; i++) // 百万次
  9. {
  10. pthread_mutex_lock(&mutex);
  11. sum++;
  12. pthread_mutex_unlock(&mutex);
  13. }
  14. return NULL;
  15. }
  16. int main()
  17. {
  18. pthread_t threads[ 10];
  19. pthread_mutex_init(&mutex, NULL);
  20. for( int i = 0; i < 10; i++)
  21. {
  22. pthread_create(&threads[i], NULL, adder, NULL);
  23. }
  24. for( int i = 0; i < 10; i++)
  25. {
  26. pthread_join(threads[i], NULL);
  27. }
  28. printf( "sum is %d\n", sum);
  29. }

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

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


 
 
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. int sum = 0;
  5. void* adder(void *p)
  6. {
  7. int old = sum;
  8. for( int i = 0; i < 1000000; i++) // 百万次
  9. {
  10. while(!__sync_bool_compare_and_swap(&sum, old, old + 1)) // 如果old等于sum, 就把old+1写入sum
  11. {
  12. old = sum; // 更新old
  13. }
  14. }
  15. return NULL;
  16. }
  17. int main()
  18. {
  19. pthread_t threads[ 10];
  20. for( int i = 0;i < 10; i++)
  21. {
  22. pthread_create(&threads[i], NULL, adder, NULL);
  23. }
  24. for( int i = 0; i < 10; i++)
  25. {
  26. pthread_join(threads[i], NULL);
  27. }
  28. printf( "sum is %d\n",sum);
  29. }

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

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

 

         不多说。

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值