InterlockedCompareExchange Release() 和 Acquire() 有什么区别?有什么区别、InterlockedCompareExchange、Release、Acqu

2023-09-07 16:14:30 作者:流年╮渲染成伤

InterlockedCompareExchangeRelease()InterlockedCompareExchangeAcquire()有什么区别?

当我尝试使用 WIN32 API 学习同步函数时,我发现有两个函数名称不同但似乎做同样的事情:

When I try to learn the synchronization functions with WIN32 API, I find there are two functions named differently but seems to do the same thing:

LONG __cdecl InterlockedCompareExchangeRelease(
  __inout  LONG volatile *Destination,
  __in     LONG Exchange,
  __in     LONG Comparand
);

LONG __cdecl InterlockedCompareExchangeAcquire(
  __inout  LONG volatile *Destination,
  __in     LONG Exchange,
  __in     LONG Comparand
);

我查看了 MSDN,上面说这些功能是:

I check the MSDN, it says those functions are:

对指定的对象执行原子比较和交换操作价值观.该函数比较两个指定的 32 位值和根据结果​​与另一个 32 位值交换比较.

Performs an atomic compare-and-exchange operation on the specified values. The function compares two specified 32-bit values and exchanges with another 32-bit value based on the outcome of the comparison.

但是对于InterlockedCompareExchangeAcquire()

该操作是通过获取内存访问语义来执行的.

The operation is performed with acquire memory access semantics.

对于InterlockedCompareExchangeRelease()

交换是使用释放内存访问语义执行的.

DevOps平台之一键发布设计

The exchange is performed with release memory access semantics.

所以我很好奇这两个函数之间的区别.何时使用获取内存访问语义或释放内存访问语义?有例子吗?

So I'm curious about the difference between these two functions. When to use the acquire memory access semantics or release memory access semantics? Are there any examples?

谢谢!

推荐答案

普通版本使用完整的屏障,而后缀版本只处理加载或存储,这在某些 CPU 上可能更快(基于 Itanium 的处理器等)

The plain version uses a full barrier while the suffixed versions only deals with loads or stores, this can be faster on some CPUs (Itanium-based processors etc)

MSDN 有一篇关于 Acquire and Release Semantics 的文章和 Interlocked* API 为以及这篇很棒的博文.Linux 内存屏障文档 也可能有用...

MSDN has a article about Acquire and Release Semantics and the Interlocked* API as well as this great blog post. The Linux memory barrier documentation might also be useful...