Free Atomic Functions

This lesson gives an overview of free atomic functions used from the perspective of concurrency in C++.

We'll cover the following

The functionality of the flag std::atomic_flag and the class template std::atomic can also be used with free functions. Because these functions use pointers instead of references, they are compatible with C. The atomic free functions are available for the types that you can use with the class template std::atomic.

There is one prominent exception to the rule: you can apply the atomic free functions to the smart pointer std::shared_ptr.


std::shared_ptr is the only non-atomic data type on which you can apply atomic operations. First, let me write about the motivation for this exception.

The C++ committee saw the necessity that instances of smart pointers should provide a minimal atomicity guarantee if they are accessed with atomic operations. What is the meaning of the minimal atomicity guarantee for std::shared_ptr? Atomic operations on std::shared_ptr will increase and decrease the reference-counter in a thread-safe way because the control block of std::shared_ptr is thread-safe. You also have the guarantee that the resource will be destroyed exactly once.


The assertion that a std::shared_ptr provides are described by Boost.

  1. A shared_ptr instance can be “read” (accessed using only const operations) simultaneously by multiple threads.
  2. Different shared_ptr instances can be “written to” (accessed using mutable operations such as operator= or reset) simultaneously by multiple threads (even when these instances are copies, and share the same reference count underneath).

To make the two statements clear, let me show a simple example. When you copy a std::shared_ptr in a thread, all is fine.

Get hands-on with 1000+ tech skills courses.