William
William

Reputation: 1895

Why do values not conflict when a thread runs the same method?

Look here:

static void Main(string[] args)
{
    test p = new test();

    new Thread(() => p.SayHello("Thread One")).Start();
    new Thread(() => p.SayHello("Thread Two")).Start();
}

then:

class test
{
    public void SayHello(string data)
    {
        int i = 0;

        while (i < 50)
        {
            Console.WriteLine("Hello from " + data);
            i++;
        }
    }
}

Why does second thread not reset the variable i to 0? and mess up the while loop which it is running on the first thread?

Upvotes: 1

Views: 131

Answers (3)

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Think of it as each thread getting it's own "copy" of the SayHello method with it's local variables. If you wanted both threads to use the same i, you'd have to pass it by reference, and then the fun would start.

Upvotes: 0

Codeman
Codeman

Reputation: 12375

It's because int i is a local variable. If you made it static to the class, rather than an local variable, it would be reset. The variable is isolated to each thread in this case.

Example:

static void Main(string[] args)
{
    test p = new test();

    new Thread(() => p.SayHello("Thread One")).Start();
    new Thread(() => p.SayHello("Thread Two")).Start();
}

public class test
{
    static int i = 0;
    public static void SayHello(string data)
    {
        i = 0;

        while (i < 50)
        {
            Console.WriteLine("Hello from " + data);
            i++;
        }
    }
}

Upvotes: 5

Brian Rasmussen
Brian Rasmussen

Reputation: 116451

i is a local variable, so each thread has its own copy of i.

Upvotes: 5

Related Questions