2020-12-18

转载    源博客地址:https://blog.csdn.net/stpeace/article/details/81150393

 

 

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

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

 
  1. #include <stdio.h>

  2. #include <pthread.h>

  3. #include <unistd.h>

  4.  
  5. int sum = 0;

  6.  
  7. void* adder(void *p)

  8. {

  9. for(int i = 0; i < 1000000; i++) // 百万次

  10. {

  11. sum++;

  12. }

  13.  
  14. return NULL;

  15. }

  16.  
  17. int main()

  18. {

  19. pthread_t threads[10];

  20.  
  21. for(int i = 0; i < 10; i++)

  22. {

  23. pthread_create(&threads[i], NULL, adder, NULL);

  24. }

  25.  
  26. for(int i = 0; i < 10; i++)

  27. {

  28. pthread_join(threads[i],NULL);

  29. }

  30.  
  31. printf("sum is %d\n", sum);

  32. }

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

  

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

 
  1. #include <stdio.h>

  2. #include <pthread.h>

  3. #include <unistd.h>

  4.  
  5. int sum = 0;

  6. pthread_mutex_t mutex;

  7.  
  8. void* adder(void *p)

  9. {

  10. for(int i = 0; i < 1000000; i++) // 百万次

  11. {

  12. pthread_mutex_lock(&mutex);

  13. sum++;

  14. pthread_mutex_unlock(&mutex);

  15. }

  16.  
  17. return NULL;

  18. }

  19.  
  20. int main()

  21. {

  22. pthread_t threads[10];

  23. pthread_mutex_init(&mutex, NULL);

  24.  
  25. for(int i = 0; i < 10; i++)

  26. {

  27. pthread_create(&threads[i], NULL, adder, NULL);

  28. }

  29.  
  30. for(int i = 0; i < 10; i++)

  31. {

  32. pthread_join(threads[i],NULL);

  33. }

  34.  
  35. printf("sum is %d\n", sum);

  36. }

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

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

 
  1. #include <stdio.h>

  2. #include <pthread.h>

  3. #include <unistd.h>

  4.  
  5. int sum = 0;

  6.  
  7. void* adder(void *p)

  8. {

  9. int old = sum;

  10. for(int i = 0; i < 1000000; i++) // 百万次

  11. {

  12. while(!__sync_bool_compare_and_swap(&sum, old, old + 1)) // 如果old等于sum, 就把old+1写入sum

  13. {

  14. old = sum; // 更新old

  15. }

  16. }

  17.  
  18. return NULL;

  19. }

  20.  
  21. int main()

  22. {

  23. pthread_t threads[10];

  24. for(int i = 0;i < 10; i++)

  25. {

  26. pthread_create(&threads[i], NULL, adder, NULL);

  27. }

  28.  
  29. for(int i = 0; i < 10; i++)

  30. {

  31. pthread_join(threads[i], NULL);

  32. }

  33.  
  34. printf("sum is %d\n",sum);

  35. }

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

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

 

         不多说。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值