I'm trying to use Interlocked.Exchange
to create a thread safe lock for some object initialize functions. Consider the below code. I want to be sure that the if
is doing the same as when the while is substituted. The reason I ask is if the code is run over and over there are times when you get an exit message before the set
message. I just would like to confirm that this is just a gui thing since the state on exit always seems to be correct.
class Program
{
private static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(() => InterlockedCheck("1")));
Thread thread2 = new Thread(new ThreadStart(() => InterlockedCheck("2")));
Thread thread3 = new Thread(new ThreadStart(() => InterlockedCheck("3")));
Thread thread4 = new Thread(new ThreadStart(() => InterlockedCheck("4")));
thread4.Start();
thread1.Start();
thread2.Start();
thread3.Start();
Console.ReadKey();
}
const int NOTCALLED = 0;
const int CALLED = 1;
static int _state = NOTCALLED;
//...
static void InterlockedCheck(string thread)
{
Console.WriteLine("Enter thread [{0}], state [{1}]", thread, _state);
//while (Interlocked.Exchange(ref _state, CALLED) == NOTCALLED)
if (Interlocked.Exchange(ref _state, CALLED) == NOTCALLED)
{
Console.WriteLine("Setting state on T[{0}], state[{1}]", thread, _state);
}
Console.WriteLine("Exit from thread [{0}] state[{1}]", thread, _state);
}
}