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?