c - 使用 CAS(Compare And Swap)时,如何确保旧值确实是旧值?

标签 c volatile cas lockless

考虑以下几点:

    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 是答案吗?

最佳答案

是的,volatile 就是这么做的(而且正是那样)。

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

关于c - 使用 CAS(Compare And Swap)时,如何确保旧值确实是旧值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9171645/

相关文章:

c - While 循环中的 If 语句出现问题

c - 如何将多行写入 C 中的输出文件?

java - !different! 之间的总订单 volatile 变量?

c# - 我如何启用CAS Dashboard (“/status/dashboard”端点)

C: 在 main 下定义函数 - 为什么编译?

c - 如何从 ctypes 传递预处理器指令?

c# - 如果我在锁定期间修改引用字段,它是否需要是 volatile 的?

JavaScript:异步事件回调的线程安全? (我需要 'volatile' 还是什么?)

java - Cas Ldap认证失败: attributes are empty

angular - 处理来自 Angular 2 的身份验证重定向