Alex Rivera | Logout

Volatile and multithreading: is the following thread-safe?

Asked 2011-07-06T06:17:11.160
24

Assume there are two threads running Thread1() and Thread2() respectively. The thread 1 just sets a global flag to tell thread 2 to quit and thread 2 periodically checks if it should quit.

volatile bool is_terminate = false;

void Thread1()
{
    is_terminate = true;
}

void Thread2()
{
    while (!is_terminate) {
        // ...
    }
}

I want to ask if the above code is safe assuming that access to is_terminate is atomic. I already know many materials state that volatile can not insure thread-safety generally. But in the situation that only one atomic variable is shared, do we really need to protect the shared variable using a lock?

Edit
Report

1 Answer

4

First, volatile is used for disabling compile optimization in c/c++. see this for understanding volatile.

The core of atomic is word align and size of is_terminate, if size of is_terminate is less than machine native size and aligned, then R and W of it is atomic.

In your context, with or without volatile, thread2 may read old value after thread1 modified it, but thread2 can read it eventually.

If eventually-read is OK for you, then your codes are thread safety.

answered 2011-07-06T07:56:27.437

Your Answer