K
K
kot25662021-11-27 18:45:58
C++ / C#
kot2566, 2021-11-27 18:45:58

Why does Thread work like this?

for (int i = 0; i < 2; i++)
            {
                Thread thread = new Thread(() =>
                {
                    Console.WriteLine("main index: " + i);
                  
                });
                thread.Start();
            }


Why is the output:
main index: 2
main index: 2

Where are the values ​​0.1?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-11-27
@kot2566

It's not the thread's fault, it's the closures .
When you refer to a variable in a lambda, it is accessed by reference.
So it turned out that at the time of launch, the value of i is already 2. You
can solve this problem if you copy the value of i into a new variable like this:

for (int i = 0; i < 2; i++)
{
    var i2 = i;
    Thread thread = new Thread(() =>
    {
        Console.WriteLine("main index: " + i2);
    });
    thread.Start();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question