【问题标题】:When using CAS (Compare And Swap), how do I ensure the old value is actually old?使用 CAS(比较和交换)时,如何确保旧值实际上是旧的?
【发布时间】:2012-02-07 05:56:00
【问题描述】:

考虑以下几点:

    int grab_next_target(int* target) { 
            do {    
                    /* Intention: store current value of *target into old, so as  
                       to ensure that old never changes */ 
                    int old = *target; 
                    /* get new value based on old -- note that old is assumed not to change here */ 
                    int new; 
                    if (1 == old) { /* imagine that old is 1 so new is now 20 */ 
                            new = 20; 
                    } else if (2 == old) { 
                            new = 300; 
                    } else if (3 == old) { 
                            new = -20; 
                    } else if (4 == old) { 
                            new = 400; 
                    } 
                    /* but the compiler has optimized 
                       old to just read from *target, so *target could be 
                       changed by another thread to be 4.  The CAS will succeed 
                       and now target will hold the wrong value (it will hold 20, instead of 400)  */ 
            } while (!AO_compare_and_swap(target, old, new)); 
    } 

我需要一种将 *target 读入局部变量的方法,并确保局部变量不会被优化为简单地成为 *target。 volatile 是一个答案吗?

【问题讨论】:

    标签: c volatile cas lockless


    【解决方案1】:

    是的,volatile 就是这么做的。

    int grab_next_target(volatile int *target) {
        ...
        int old = *target; // Guaranteed to access "target" exactly once
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多