There are 2 threads, one of which reads data from a variable of type bool, and the other can change its value.

Are these two operations atomic to each other?

And if not, then tell me, please, any standard wrapper to make exclusive access to this variable. Of course, you can make an access method that would synchronize access, but I don’t want to reinvent the wheel.

Used Unix OS

    2 answers 2

    • Operations cannot be atomic with respect to each other, they are either atomic or non-atomic.

    • Actually, if you reformulate your question as “Are read and write for bool atomic?”, Then you can try to answer it.

    • And the answer is quite simple - no, they are not.

    • The atomicity of these operations is not specified anywhere, since it depends on the architecture of the machine on which the compiled code is executed. So, reading a bool in an unaligned case may well lead to the generation of 2+ instructions.

    • The second problem is cache coherence. The operation must be invariant with respect to all caches of the processor, which means that it potentially ceases to be atomic.


    • Now a little closer to practice. In the new C++11 standard, std::atomic_bool should be used to ensure atomicity of operations on integral types .

    • If boost used, then personally I would (not familiar with your task and poking a finger into the sky) organized synchronization when working with a variable of type bool with the help of boost::condition_variable .

    • Perhaps you can use (specific to WinAPI ) Interlocked functions for accessing a variable or, for example, some classic synchronization mechanism such as the Critical Section.

    • ...


    • More details about the atomic nature of read / write operations, their architecture and Microsoft-specific promises regarding the use of volatile can be found here and here.
    • 2
      I will add that in gcc (since we are talking about Unix, then it is quite likely) there are atomic builtins . It is like some kind of analogue of interlocked functions. - drdaeman
    • @ Kotik_hokhet_kusat, how do you know all this .... - AseN
    • 2 @drdaeman: this is called sleight of hand and no fraud :) - jmu

    The most typical race case. Just so these operations will not be atomic. Mutexes or semaphores must be used for synchronization. The concrete implementation depends on the operating system, as well as how you organize multithreading: using low-level APIs or wrappers.