Interlock.CompareExchange在if语句内是原子的吗?

huangapple go评论58阅读模式
英文:

Is Interlock.CompareExchange atomic inside an if statement?

问题

I am assuming that the piece of code is threadsafe,

if ((Interlocked.CompareExchange(ref semaphore, 1, 0) == 0))
{
  //Do Stuff
  semaphore = 0;
}

However I am wondering why:

In my mind I see this as two operations,

  1. First it compares the semaphore with the value, and replaces it if they are equal
    (Interlocked.CompareExchange(ref semaphore, 1, 0)

  2. Then it compares the value it returns to 0, with the statement {CompareExchange} == 0

Can not the semaphore be set somewhere else, before the second comparison (2.) happens? And that the function gets entered when it should not?

英文:

I am assuming that the piece of code is threadsafe,

if ((Interlocked.CompareExchange(ref semaphore, 1, 0) == 0))
{
  //Do Stuff
  semaphore = 0;
}

However I am wondering why:

In my mind I see this as two operations,

  1. First it compares the semaphore with the value, and replaces it if they are equal
    (Interlocked.CompareExchange(ref semaphore, 1, 0)

  2. Then it compares the value it returns to 0, with the stamement {CompareExchange} == 0

Can not the semaphore bet set somewhere else, before the second comparison (2.) happens? And that the function gets entered when it should not?

答案1

得分: 3

Interlocked.CompareExchange 是一个原子操作,会返回一个值。一旦发生这个操作,该方法调用的结果不会改变,除非再次调用 Interlocked.CompareExchange,即使 semaphore 改变也不影响。这与它是否在 if 语句内无关;您可以依赖该返回值保持稳定。

英文:

Interlocked.CompareExchange is an atomic operation, resulting in a return value. Once that happens, the result of that method call cannot change unless you call Interlocked.CompareExchange again, even if semaphore changes. It doesn't matter that it is inside an if statement; you can depend on that return value to be stable.

huangapple
  • 本文由 发表于 2023年3月15日 18:11:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定