Search⌘ K
AI Features

std::atomic_ref

Explore the use of std atomic ref in C++20 to improve thread safety by applying atomic operations directly on referenced objects. Understand how it overcomes data race issues in concurrent programming, with practical examples illustrating its advantages over copying atomic values.

We'll cover the following...

Atomics receives a few important extensions in C++20. Probably the most important ones are atomic references and atomic smart pointers.

Introduction

The class template std::atomic_ref applies atomic operations to the referenced object. Concurrent writing and reading of atomic object ensures that there is no data race. The lifetime of the referenced object must exceed the lifetime of the atomic_ref. When any atomic_ref is accessing an object, all other accesses to the object must use an atomic_ref. In addition, no sub-object of the atomic_ref-accessed object may be accessed by another atomic_ref.

Motivation

Stop. You may think that using a reference inside an atomic would do the job. Unfortunately not.

In the following program, I have a class ExpensiveToCopy, which includes a counter. The counter is concurrently ...