Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I read a bool variable in a thread without mutex? [duplicate]

Is there anything wrong in following source code if I don't use mutex?

bool bStop = false;

void thread1_fun()
{
    while (!bStop)
    {
        doSomething();
    }
}

void thread2_fun()
{
    bStop = true;
}
like image 670
tillman Avatar asked Dec 18 '17 11:12

tillman


People also ask

Is bool thread safe C++?

It's more of a C question then a Rust question. But, no, it's not safe. You should use atomics or mutexes for synchronization.

Does read need mutex?

It depends. The C++ language says nothing about threads or atomicity. But on most modern CPU's, reading an integer is an atomic operation, which means that you will always read a consistent value, even without a mutex.

Is bools thread safe?

None of these are thread-safe. The thread that calls the getter will always read a stale value. How stale it is depends on the processor and the optimizer.

Is volatile bool thread safe?

Updating a bool is always thread safe, if you never read from it. And if you do read from it, then the answer depends on when you read from it, and what that read signifies. On some CPUs, but not all, writes to an object of type bool will be atomic. x86 CPUs will generally make it atomic, but others might not.


Video Answer


1 Answers

It is undefined behaviour to write to an object in one thread while another thread accesses the object at all.

Unless you specifically inform the compiler that there should be a fence, such as the use of std::atomic, std::mutex et al, all bets are off.

The compiler is within its rights to re-write the code as this:

bool bStop = false;

void thread1_fun()
{
    const bool stopped = bStop;
    // compiler reasons: "because there is no fence, the variable clearly cannot
    // have changed to true, since no-other thread will modify it, since
    // to modify it without a fence would be UB." 
    while (!stopped)  
    {  
        doSomething();
    }
}

void thread2_fun()
{
    // this happens in my thread's view of the world, 
    // but no other thread need see it.
    bStop = true;  
} 
like image 116
Richard Hodges Avatar answered Sep 28 '22 08:09

Richard Hodges