liveBook · Manning

Is_lock_free()

As explained in C++ Concurrency in Action, Second Edition

`is_lock_free()` is an atomic member function that reports whether operations on an atomic object are lock-free.

`is_lock_free()` reports whether operations on a particular atomic object are lock-free: `true` means they use atomic instructions directly, while `false` means the implementation uses an internal lock. This check matters when choosing atomics as a performance alternative to mutex-based synchronization. section 5.2.1 section 5.2.3

Checking an atomic boolean

Call `flag.is_lock_free()` on a `std::atomic<bool>` object to check whether its operations are lock-free. The type may use an internal mutex, so the result can guide whether an atomic-based implementation is likely to deliver the expected performance benefit. section 5.2.3

Use the result to inform implementation choices:

  • If the check returns false, atomic operations may be emulated using an internal lock; a mutex-based implementation may be easier to get right and may avoid the hoped-for performance loss. section 5.2.1
  • The check applies to a particular object. For a compile-time guarantee across supported hardware, C++17 provides `std::atomic<T>::is_always_lock_free`. section 5.2.1

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Defines the result and its performance implication, but does not explain the implementation of atomic instructions or internal locks.
Examples
Checks whether operations on a std::atomic<bool> object are lock-free.
What you can do after
Evaluate whether an atomic object is lock-free and consider a mutex-based alternative when it is not.
How it connects
Connects atomic operations with mutexes, lock-free data structures, and the distinction between std::atomic<bool> and std::atomic_flag.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.