以下两个引文似乎相互矛盾:
https://www.kernel.org/doc/Documentation/atomic_ops.txt
int atomic_cmpxchg(atomic_t *v, int old, int new);
This performs an atomic compare exchange operation on the atomic value v, with the given old and new values. Like all atomic_xxx operations, atomic_cmpxchg will only satisfy its atomicity semantics as long as all other accesses of *v are performed through atomic_xxx operations.
atomic_cmpxchg requires explicit memory barriers around the operation.
对比
https://www.kernel.org/doc/Documentation/memory-barriers.txt
Any atomic operation that modifies some state in memory and returns information about the state (old or new) implies an SMP-conditional general memory barrier (smp_mb()) on each side of the actual operation (with the exception of explicit lock operations, described later). These include:
<...> atomic_xchg(); atomic_cmpxchg(); <...>
These are used for such things as implementing LOCK-class and UNLOCK-class operations and adjusting reference counters towards object destruction, and as such the implicit memory barrier effects are necessary.
那么应该在
atomic_xchg()
周围放置内存屏障吗?手动?
最佳答案
我还不知道 Linux 内核编程的细节,所以这里有一个部分(一般)答案。
在 x86 上,此操作带有完整的内存栅栏,在 mfence
中不需要/lfence
/sfence
附近cmpxchg
操作。
在具有宽松内存模型的其他架构上,它可以与其他内存语义耦合,例如“释放”,取决于如何atomic_cmpxchg()
被转换为操作码。
它在处理器方面。但是,编译器也可以对操作进行重新排序,因此如果 atomic_cmpxchg()
不隐含编译器屏障(例如 __asm__ __volatile__
),你需要一个。
关于multithreading - atomic_cmpxchg() 是否意味着内存障碍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20950603/