Why is only std :: atomic_flag guaranteed to lock?

From C ++ Concurrency in Action:

the difference between std :: atomic and std :: atomic_flag is that std :: atomic cannot be locked; implementations may have to acquire a mutex internally to ensure that operations are atomic

I wonder why. If atom_flag is guaranteed to be blocked, then why isn't it guaranteed to be atomic<bool>

? Is it because of the member function compare_exchange_weak

? I know some machines are missing one compare and exchange command, is that the reason?

+3


source to share


2 answers


First of all, you are perfectly allowed to have something like std::atomic<very_nontrivial_large_structure>

, so std::atomic

as such usually cannot be guaranteed by locking (although most specializations are for trivial types, such as, bool

or int

probably can, on most systems). But this is somewhat unrelated.

The exact reason why atomic_flag

and should not be blocked is indicated in the note in N2427 / 29.3:



Therefore, transactions must be without addresses. No other type requires locking, and therefore atom_flag is the minimum hardware type required to comply with this standard. The remaining types can be emulated using atom_flag , but with less ideal properties.

In other words, this is the minimum thing that should be guaranteed on every platform, so the standard can be properly implemented.

+5


source


The standard does not guarantee that atomic objects are locked. On a platform that does not provide blocking atomic operations for objects of a type T

, std::atomic<T>

it can be implemented using a mutex that will not block. In this case, any containers using these objects in their implementation will not be blocked either.

The standard provides the ability to check if a variable is not std::atomic<T>

locked: you can use var.is_lock_free()

or atomic_is_lock_free(&var)

. For basic types like int, there are also macros (for example ATOMIC_INT_LOCK_FREE

) that indicate whether kernel access is available on that type.



std::atomic_flag

is an atomic boolean type. Almost always, a type boolean

does not need to use a mutex or any other way of synchronization.

+1


source







All Articles