SRF
SRF

Reputation: 979

Reading a Global Variable from a Thread and Writing to that Variable from another Thread

My program has 2 threads and a int global variable. One thread is reading from that variable and other thread is writing to that variable. Should I use mutex lock in this situation.

These functions are executing from 2 threads simultaneously and repetitively in my program.

void thread1()
{
    if ( condition1 )
        iVariable = 1;
    else if ( condition2 )
        iVariable = 2;
}

void thread2()
{
    if ( iVariable == 1)
        //do something
    else if ( iVarable == 2 )
        //do another thing

}

Upvotes: 0

Views: 526

Answers (2)

Hans Passant
Hans Passant

Reputation: 941545

If you don't use any synchronization then it is entirely unpredictable when the 2nd thread sees the updated value. This ranges somewhere between a handful of nanoseconds and never. With the never outcome being particularly troublesome of course, it can happen on a x86 processor when you don't declare the variable volatile and you run the Release build of your program. It can take a long time on processors with a weak memory model, like ARM cores. The only thing you don't have to worry about is seeing a partially updated value, int updates are atomic.

That's about all that can be said about the posted code. Fine-grained locking rarely works well.

Upvotes: 1

Missaka Wijekoon
Missaka Wijekoon

Reputation: 891

Yes you should (under most circumstances). Mutexes will ensure that the data you are protecting will be correctly visible from multiple contending CPUs. Unless you have a performance problem, you should use a mutex. If performance is an issue, look into lock free data structures.

Upvotes: 1

Related Questions