atomic_cmpxchg()是否意味着内存屏障?

7
以下两个引用似乎相互矛盾:

https://www.kernel.org/doc/Documentation/atomic_ops.txt

int atomic_cmpxchg(atomic_t *v, int old, int new);

这个函数对原子变量v执行一个比较并交换的操作,使用给定的旧值和新值。与所有的atomic_xxx函数一样,只有在所有对*v的访问都通过atomic_xxx函数进行时,atomic_cmpxchg才能满足其原子性语义。

atomic_cmpxchg需要显式地在操作周围设置内存屏障。

vs

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() 周围放置内存屏障?

1个回答

3

我还不了解Linux内核编程的具体细节,因此这是一个部分(通用)答案。

在x86上,这个操作会带有完整的内存屏障,不需要在cmpxchg操作周围使用mfence/lfence/sfence

在其他松散内存模型的架构上,它可以与其他内存语义耦合,例如“释放”,这取决于如何将atomic_cmpxchg()转换为操作码。

这是处理器方面的事情。但是,也有编译器可以重新排序操作,因此如果atomic_cmpxchg()没有暗示编译器屏障(例如__asm__ __volatile__),则需要一个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接