How do I use atomic_ref and memory_order_relaxed/acquire/release?

In C++, std::atomic_ref is a lightweight, non-intrusive way to create atomic views of non-atomic objects. It allows developers to safely share and manipulate these objects across different threads. The memory order you choose (such as memory_order_relaxed, memory_order_acquire, and memory_order_release) defines how operations on these objects will behave in a multi-threaded environment.

Using atomic_ref with Different Memory Orders

Here's a brief overview of the memory orders:

  • memory_order_relaxed: No synchronization or ordering guarantees.
  • memory_order_acquire: Ensures all previous operations in the current thread are visible to other threads acquiring the same atomic variable.
  • memory_order_release: Ensures that all previous operations in the current thread will be visible to other threads that subsequently acquire the same atomic variable.

Example

#include <atomic> #include <iostream> int main() { int x = 0; std::atomic_ref atomic_x(x); // Thread 1 atomic_x.store(10, std::memory_order_relaxed); // Thread 2 int y = atomic_x.load(std::memory_order_acquire); std::cout << "Value of y: " << y << std::endl; // Store and release atomic_x.store(20, std::memory_order_release); return 0; }

atomic_ref memory_order C++ multi-threading relaxed acquire release