0

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?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Somecode
  • 15
  • 1
  • 4
  • 2
    You're setting `semaphore` in the `if`, which doesn't really seem to make sense: it's already being set (in a thread-safe way) by the `CompareExchange`. – 500 - Internal Server Error Mar 15 '23 at 10:18
  • 3
    The whole point of the return value from `CompareExchange` is it returns the previous value as it was at the time of the exchange - information you could not obtain by re-reading the variable yourself because, as you say, it might have been changed in the meantime. – Damien_The_Unbeliever Mar 15 '23 at 10:20
  • What is the intention of your code? Is it to provent concurrent executions of the `//Do Stuff` by more than one threads? In that case check out [this](https://stackoverflow.com/questions/75728657/is-it-safe-to-use-the-interlocked-compareexchange-as-a-lock-only-for-enter-not "Is it safe to use the Interlocked.CompareExchange as a lock, only for enter, not for exit?") recent question. – Theodor Zoulias Mar 15 '23 at 11:09
  • "*Can not the semaphore bet set somewhere else,...*" -- The meaning of this phrase is obscure to me. Is the "bet" a typo? – Theodor Zoulias Mar 15 '23 at 11:12

1 Answers1

3

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.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501