If I’m on hardware with atomic read and increment/decrement support, can I use a volatile sig_atomic_t in C++03 to get access to the atomic operations and avoid a full blown mutex or must I wait for C++11 and std::atomic<int>?
If I’m on hardware with atomic read and increment/decrement support, can I use a
Share
Some compilers provide non-standard semantics for
volatilewhich would allow that to work, but it’s not portable.volatileis for accessing hardware, not for inter-thread communication. There is no guarantee that a write to avolatilevariable by one thread will ever become visible to another thread — for communication between threads you need synchronising operations such as memory barriers, which are provided by operations onstd::atomictypes.For more info see “volatile vs. volatile” and Hans Boehm’s ISO C++ paper “Should volatile Acquire Atomicity and Thread Visibility Semantics?” (both links taken from the footnote to a recent Herb Sutter blog post)
You don’t have to wait for C++11 support in your compiler though, most platforms provide some platform-specific atomic operations that also include any necessary memory barriers, e.g. GCC’s
__syncbuilt-in, Solaris’ atomic operations, or Win32’s Interlocked functions. There are also portable libraries such as the proposed Boost.Atomic which provide a common interface to platform-specific implementations.