-1

Here it goes a tricky one (maybe not for experts). I'm learning about concurrency in C# and I'm playing around with some dummy code to test the fundamentals of threads. Im surprised about how is possible that the following code prints the value 10 sometimes.

Thread[] pool = new Thread[10];

for(int i = 0; i < 10; i++)
{
   pool[i] = new Thread(() => Console.Write(i));
   pool[i].Start();
}

Typical output is like 76881079777. I know is the value 10 and not 1 and 0 because the for loop body executes 10 times (not strictly sure, but I couldn't break C#). I'm even more surprised why this does not throw an IndexOutOfRange exception in the statement pool[i] = new Thread(() => Console.Write(i));

As long as I know, the for loop executes like following:

  1. Check the condition ( i < 10)
  2. Executes the body if condition is true
  3. Increments the control variable (i++)
  4. Repeat

So, assuming that, is imposible for me to understand how the body can be executed with the value 10. Any ideas?

1 Answers1

3

When you call pool[i].Start();, it does not mean that () => Console.Write(i) gets executed immediately. Instead, the operating system gets to decide when the passed method gets executed (this is also called "scheduling"). For instance, the operating system may decide to execute one of your threads after your loop is done. In this case, i is 10; so this is the reason why an output of 10 might be possible.