Home

multithreading (unexpected?) behavior

Hi,

I'm using the following query below. I expect the code to print:

"
start
done
end
"

This happens every time I change the code and compile/run it for the first time. But from the second time the code is run without any changes the second line "done" is not printed. It seems that the secondary thread is entering the locked code first but that Console.WriteLine output is not shown.

I was wondering if this is expected behavior and I'm missing something?

Thanks,
void Main()
{
	ThreadTest.Main();
}

// Define other methods and classes here
class ThreadTest
{
	static bool _done = false;
	static readonly object _locker = new object();
	
	public static void Main()
	{
		Console.WriteLine("start");
		Thread t = new Thread(Go);
		t.Start();
		Go();
		t.Join();
		Console.WriteLine("end");
	}
	
	static void Go()
	{
		lock (_locker)
		{
			if (!_done)
			{
				Console.WriteLine("Done");
				_done = true;
			}
		}
	}
}

Comments

Sign In or Register to comment.