Given a scenario where there's a function that should only be executed by one thread at any given time, and the rest just return (since a specific state is already being worked on), what's the best way to accomplish this?
public void RunOnce()
{
if(Interlocked.Exchange(ref m_isRunning, 1) == 1)
return;
// Run code that should only be executed once
// What mechanism do we use here to ensure thread safety?
Volatile.Write(ref m_isRunning, 0);
}
Would the same mechanism apply if m_isRunning is a state (ie. an integer representing an enum)?
The code in your question is thread-safe IMHO, but in general the
Interlocked.CompareExchangemethod is more flexible than theInterlocked.Exchangefor implementing lock-free multithreading. Here is how I would prefer to code theRunOncemethod:My suggestion though would be to use the
Monitorclass:...or the
SemaphoreSlimclass if you prefer to prevent reentrancy:It makes the intentions of your code cleaner IMHO.