0

I recently was under interview conditions (white boarding) and was asked to detail a task that still has me thinking about it now.

The premise was simple - and no doubt hardly novel.

   //main
   for (int i = 1; i < 6; i++)
   {
        Thread t = new Thread(() => ThreadWork.MemberMethod(i));
        t.Start();             
   }

   static class ThreadWork
   {
        public static void MemberMethod(int i)
        {
            Console.WriteLine(i);
        }
   }

A pretty standard question about thread synchronicity - why is the output variable and not 1-2-3-4-5 every time? I gave a rough answer about creating a callback structure using delegates so that each previous threads execution had concluded before firing the next. Truth be told, I didn't field the question too well.

My answer was somewhat along these lines -

delegate void Del(int i);

//main
Del handler = ThreadWork1.MemberMethod;
for (int i = 1; i < 6; i++)
{
       Thread t = new Thread(() => handler(i));
       t.Start();
}

static class ThreadWork1
{
    public static void MemberMethod(int i)
    {
        Console.WriteLine(i);
    }
}

Running it now, I can see that this method does not work, at least in its current iteration.

I found an example from a blog that suggested using locks, a quick modification later and I had this:

//main
ThreadWork2 threadwork = new ThreadWork2();
for (int i = 1; i < 6; i++)
{
    Thread t = new Thread(() => threadwork.MemberMethod(i));
    t.Start();
}

class ThreadWork2
{
    public void MemberMethod(int i)
    {
        lock (this)
        {
            Console.WriteLine(i);
        }
    }
}

Yielded similar result - variance in output.

Am I close with any of these attempts? Or should I consider an entirely different approach.

James
  • 356
  • 2
  • 13
  • There are likely two reasons why. The first is that the threads don't necessarily execute in order (i.e. no guarantee that Thread 1 will be writing to the console before Thread 2). The second (the more likely main issue) is the duplicate. – mjwills Sep 10 '19 at 11:05
  • There is also no point locking around `Console.WriteLine`. It does its own internal locking. – mjwills Sep 10 '19 at 11:10

0 Answers0