'C# Multithreading Pass by value or reference?
I saw a piece of code online that states that calling a thread like this causes non-deterministic output "0223557799" or something of this kind.(You get the point)
for (int i = 0; i < 10; i++)
new Thread (() => Console.Write (i)).Start();
This is the reason given for this:
"The problem is that the 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!"
But, conventionally speaking when the argument is passed by value - each new Thread call should send i its incremental order right ? Only if values are pass by reference the above mentioned reason holds good. So, in C# Multi-Threading, are the values pass by reference ?
I'm new to C#,Please understand if the question is naive.
Solution 1:[1]
There is more than one problem here. It certainly starts with the for() loop variable capture problem, described in this blog post. This tends to produce "10" as the output, but there's no guarantee this happens since a thread may execute while the loop is still being iterated.
But the program also suffers for a core threading problem, there's no guarantee whatsoever that the threads will call Console.Write() in the expected order. It is merely likely, but one thread may race ahead of another and acquire the lock that protects the console. A problem known as a "threading race".
Solution 2:[2]
Your program is equivalent to the following program:
class Locals
{
public int i;
public void M() { Console.Write(this.i);
}
...
Locals locals = new Locals();
for (locals.i = 0; locals.i < 10; locals.i++)
new Thread (locals.M).Start();
Now is it clear why you get the results you do? It is not i that is being passed by value; rather it is locals that is being passed by reference to each thread. Each thread is sharing locals.i and therefore can see the current value of locals.i, not the value that i was when the thread was created.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
