std::atomic<bool>

This lesson gives an overview of std::atomic<bool> which is used from the perspective of concurrency in C++.

We'll cover the following

Let’s start with the full specializations for bool: std::atomic<bool>

std::atomic<bool>

std::atomic<bool> has a lot more to offer than std::atomic_flag. It can explicitly be set to true or false.

atomic is not volatile

What does the keyword volatile in C# and Java have in common with the keyword volatile in C++? Nothing! It’s so easy in C++. That is the difference between volatile and std::atomic.

  • volatile: is for special objects, on which optimized read or write operations are not allowed

  • std::atomic: defines atomic variables, which are meant for a thread-safe reading and writing

It’s so easy, but the confusion starts exactly here. The keyword volatile in Java and C# has the meaning of std::atomic in C++, i.e. volatile has no multithreading semantic in C++.

volatile is typically used in embedded programming to denote objects which can change independently of the regular program flow. One example is an object which represents an external device (memory-mapped I/O). Because these objects can change independently of the regular program flow and their value will directly be written into main memory, no optimized storing in caches takes place.

This is sufficient to synchronize two threads, so I can implement a kind of condition variable with an std::atomic<bool>. Therefore, let’s first use a condition variable.

Get hands-on with 1200+ tech skills courses.