liveBook · Manning

Std::atomic<bool>

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

A C++ standard library atomic type that provides atomic operations on a Boolean value.

std::atomic<bool> stores a Boolean value and can be initialized or assigned from a plain bool. Assignment returns the stored bool, not a reference to the atomic object. section 5.2.3

Its main operations cover querying, writing, and conditional updates:

  • Read the value with load() or an implicit conversion to bool. section 5.2.3
  • Write true or false with store(); replace the value and retrieve its previous value with exchange(). section 5.2.3
  • Use compare-exchange to store a new value only when the current value equals an expected value. These operations can take memory-order arguments. section 5.2.3

Conditionally set a flag

The loop attempts to change b to true while compare_exchange_weak fails and expected remains false. section 5.2.3

std::atomic<bool> b;
bool x=b.load(std::memory_order_acquire);
b.store(true);
x=b.exchange(false,std::memory_order_acq_rel);

See load, store, and exchange used with a Boolean atomic, including explicit memory-order arguments. section 5.2.3

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

How deep it goes
Defines initialization and assignment, then distinguishes load/store, exchange, and conditional compare-exchange operations.
Examples
Uses Boolean assignment, load/store, exchange, and compare-exchange examples.
What you can do after
Apply C++ atomic operations to read, replace, or conditionally update a Boolean value.
How it connects
Contrasts with std::atomic_flag and connects atomic operations to memory ordering.

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.