RStyle RStyle - 2 months ago 23
C# Question

Threadlocal values iList ordering

Hi i have an example which creates 2 threads. My question is when i output the values it always prints 1000 before 999. Is it possible to print 999 before 1000. Just want to know how are they ordered?

static void Main(string[] args)
{
ThreadLocal<int> field = new ThreadLocal<int>(() => 0, true);



Thread firstThread = new Thread(new ThreadStart(() =>
{

field.Value = 999;
}));
Thread secondThread = new Thread(new ThreadStart(() =>
{

field.Value = 1000;
}));


firstThread.Start();
secondThread.Start();


firstThread.Join();
secondThread.Join();

IList<int> valueList = field.Values;

foreach (int arr in valueList)
Console.WriteLine(arr);


Console.Read();
}

Answer

Generally you shouldn't write multi-threaded code of which threads depend on which finishes first.

But your requirement can be achieved with a Semaphore/WaitHandle

//Creates semaphore with 1 possible owner and the owner slot taken
var sema = new Semaphore(1, 1);

Thread firstThread = new Thread(new ThreadStart(() =>
{
        //Value set and sema is released, if this thread calls release
        //before `secondThread` attempts to acquire then there will be no stalling
        field.Value = 999;
        sema.Release();
}));

Thread secondThread = new Thread(new ThreadStart(() =>
{
        sema.WaitOne();
        field.Value = 1000;
}));

Have a read of this Book (The Little Book of Semaphores): Chapter 3 - Basic synchronization patterns for more information on basic signaling/waiting: http://www.greenteapress.com/semaphores/downey08semaphores.pdf