Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the implementation of std::atomic with respect to locks change a program's behavior from correct to incorrect?

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 :-)

like image 628
razeh Avatar asked Jan 12 '14 14:01

razeh


People also ask

What does std :: atomic do?

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).

Is atomic thread safe C++?

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.

What does atomic do in C++?

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.

Is Atomic faster than mutex?

Summing up, in general atomic operations are faster if contention between threads is sufficiently low.


1 Answers

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.

like image 79
axe Avatar answered Oct 28 '22 06:10

axe