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,
First it compares the semaphore with the value, and replaces it if they are equal
(Interlocked.CompareExchange(ref semaphore, 1, 0)
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?
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.