繁体   English   中英

使用CAS(比较和交换)时,如何确保旧值实际上是旧值?

[英]When using CAS (Compare And Swap), how do I ensure the old value is actually old?

考虑以下:

    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读入局部变量的方法,并确保该局部变量不会被简单地*目标所优化。 易失性答案吗?

是的,那正是volatile所做的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM