Search code examples
c++booleanatomic

Can I avoid locking a bool if it only goes from false to true once?


I have a bool that is being accessed by multiple threads, but that value can only transition from false to true, once, during the runtime of a program. So long as the value is eventually true, I don't care of each thread has an immediately consistent view of the variable--as long as they all eventually pick it up.

Unfortunately, checking the value of this value is called pretty frequently, so locking around the value is expensive.

I've seen other posts where people have talked about the cache may not be refreshed correctly, but what are the exact side effects of not locking on reads?

Thanks!


Solution

  • The exact side effect is undefined behavior.
    With a regular bool, the compiler is not aware that it will be accessed in multiple threads and therefore it may apply optimizations that lead to undefined behavior (such as an update not visible to other threads).

    Replace bool with std::atomic<bool>, use it exactly like you would have used bool and you are fine. No locking necessary.