for (int i = 0; i < 10; i++)
new Thread (() => Console.Write (i)).Start();
As expected the output of the above code is non-deterministic, because i variable refers to the same memory location throughout the loop’s lifetime. Therefore, each thread calls Console.Write on a variable whose value may change as it is running
However,
for (int i = 0; i < 10; i++)
{
int temp = i;
new Thread (() => Console.Write (temp)).Start();
}
Is also giving non-deterministic output! I thought variable temp was local to each loop iteration. Therefore, each thread captured a different memory location and there should have been np problem.
Your program should have 10 lambdas, each writing one of the digits from 0 to 9 to the console. However, there’s no guarantee that the threads will execute in order.