Monday, March 21, 2011

Question a Threading

I cannot believe somebody ask the expected result regarding threading.
I came across to find out and prove if he is correct.

The code snippet :


class Program
{
static void Main(string[] args)
{
Thread s1 = new Thread(Display1);
Thread s2 = new Thread(Display2);

s1.Start();
s2.Start();
for (var i = 0; i <= 10; i++)
{
Console.WriteLine(string.Format("Main 1 : {0}", i.ToString()));
}

Console.ReadKey();
}

static void Display1()
{
for (var i = 0; i <= 10; i++)
{
Console.WriteLine(string.Format("Display 1 : {0}", i.ToString()));
}
}

static void Display2()
{
for (var i = 0; i <= 10; i++)
{
Console.WriteLine(string.Format("Display 2 : {0}", i.ToString()));
}
}
}


According to the questionaire, the correct answer would be
1. Display 1: 0 to Display 1: 10
2. Main 1: 0 to Main 1: 10
3. Display 2: 0 to Display 2: 10

As I execute the code, it seems to negate the statement. It would display, different display everytime I will execute. This is because, there is a timing or a specific period of time where a thread will start. But most of the time, it should go as expected.

some output :



If anybody wants to understand and have a good start regarding THREADING.
you can start from here.

http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

No comments: