Reputation: 43159
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>
?
Upvotes: 1
Views: 1181
Reputation: 171343
Some compilers provide non-standard semantics for volatile
which would allow that to work, but it's not portable. volatile
is for accessing hardware, not for inter-thread communication. There is no guarantee that a write to a volatile
variable 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 on std::atomic
types.
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 __sync
built-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.
Upvotes: 5