Curry
Curry

Reputation: 11

Unexpected result when two threads accessing a global variable

I have two threads, t1 and t2.
They both do add operation on a global variable named 'count', which was initialized with 0.
t1 does count++ and t2 does count+=100. I start t1 first then t2, but the output result doesn't meet my expectation. Is there I misunderstand something?

It won't help even though I used lock() in two threads.

Here's the C# code:

private int count = 0;
private object locker = new object();

void run()
{
    var t1 = new Thread(Add_1);
    var t2 = new Thread(Add_2);
    t1.Start();
    t2.Start();
}
void Add_1()
{
    lock(locker)
    {
        count++;
        Console.WriteLine(count);
    }
}

void Add_2()
{
    lock(locker)
    {
        count += 100;
        Console.WriteLine(count);
    }
}

It sometimes prints

1
101

or

100
101

I don't have any idea of that. In my opinion, t1 should have the locker until it finished its job. But it seems that t2 has chance to add count earlier than t1.

Hope someone can give me a hand, thanks.

Upvotes: 0

Views: 204

Answers (1)

Tistkle
Tistkle

Reputation: 500

What's wrong? Actually, the order you define, or start, in your code, doesn't tell your computer how to execute. In fact, you have two completely separated threads and your VM/Processor can execute it in any order. A lock don't tell it what's the correct execution order, but only that one Thread is in, other threads have to wait.

So, your program works fine. If you want to execute it in an order, you don't need threads, or you can use any async/await method to sync them, or you can put one to sleep.

Maybe, you want to take a look at these articles

Upvotes: 1

Related Questions