Advanced atomic operations in C++

Exploring std::memory_order and some other atomic-related things

CMP

--

Introduction

In the previous article, I discussed the basics of C++ atomic operations for concurrency using std::atomic from the <atomic> header introduced in C++11. std::atomic allows programmers to safely operate on data that is shared by multiple threads, ensuring that each operation is indivisible and cannot be interrupted by other threads. Atomicity of an individual operation is important, but what about the ordering of multiple atomic operations? Will all of the threads observe the operations in the same order?

In this article, we’ll dive deeper into the usage of atomic operations beyond the basics, including memory ordering. Additionally, we’ll look at the new member functions added to std::atomic in C++20, as well as some other details not mentioned in the previous article.

More simple operations

In the previous article, I went over some of the basic, foundational operations using std::atomic, such as load and store. However, there are several operator overloads that I did not discuss previously, so let’s go over those before getting into the complicated parts of this article.

In non-atomic scenarios, it is generally well known that operator++ increments a value and operator+= adds a value to the existing value. Similar operations exist for decrement operations, as well as for bitwise operations like operator&=.

--

--