Are there C++ programs that are correct and deadlock free when atomic::is_lock_free
returns true, but are undefined or could contain a deadlock when atomic::is_lock_free
returns false?
Given that any lock inside an atomic will be acquired and released under the library's control, I can't imagine how to muck things up, but with multithreading and locks there is usually a way :-)
std::atomic. Each instantiation and full specialization of the std::atomic template defines an atomic type. If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races).
In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.
C++ Atomic Variables Objects of type Atomic are protected from data races, and if one thread tries to write to atomic objects while another thread is extracting values from it, the result is well defined. This comes from the fact that atomic operations modify data on a single clock tick.
Summing up, in general atomic operations are faster if contention between threads is sufficiently low.
In order to have deadlock in a program you need to hold more then one lock simultaneously. Accessing or modifying std::atomic<T>
variable may acquire lock according to the C++11 standard, but it releases the lock as soon as function call finished and it doesn't call any user defined function while holding a lock, so you can't have a situation where two (or more) mutexes are locked simultaneously; hence no deadlock is possible with std::atomic
internal lockable objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With