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.