In my application, I have an int and a bool variable, which are accessed (multiple write/read) by multiple threads. Currently, I am using two mutexes, one for int and one for bool to protect those variables.
I heard about using atomic variables and operators to write lock-free multi-thread program. My questions are
- What’s the definition of atomic variables and operators?
- What’s the main difference between std::atomic and
boost/atomic.hpp? Which one is more standard or popular? - Are these libraries platform-dependent? I am using gnu gcc 4.6 on
Linux at the moment, but ideally it shall be cross-platform. I heard that the definition of “atomic” actually depends on the hardware as well. Can anyone explain that as well? - What’s the best way to share a bool variable among multiple threads? I would prefer not to use the “volatile” keyword.
Are these code thread-safe?
double double_m; // double_m is only accessed by current thread.
std::atomic<bool> atomic_bool_x;
atomic_bool_x = true && (double_m > 12.5);
int int_n; // int_n is only accessed by current thread.
std::atomic<int> atomic_int_x;
std::atomic<int> atomic_int_y;
atomic_int_y = atomic_int_x * int_n;
I’m not an expert or anything, but here’s what I know:
std::atomicsimply says that callingloadandstore(and a few other operations) concurrently is well-defined. An atomic operation is indivisible – nothing can happen ‘in-between’.std::atomicis based off ofboost::atomic. If you can, usestd, otherwise useboost.stdbeing completely so, however your compiler will need to support C++11std::atomic_bool. You should not need to use volatile.Also, I believe
load/storediffers fromoperator=/operator Tonly.load/storeare atomicNevermind. I checked the standard and it appears that the operators are defined in terms of
load/store/etc, however they may return different things.Further reading: