Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Memory Model Basic

Kohei Otsuka
Level Up Coding
Published in
10 min readDec 18, 2020

--

Photo by Andrew Ridley on Unsplash

Introduction

As many know, since C++11, std::atomic<T> was introduced as a part of the standard library. Probably the most obvious part of the functionality is that each instantiated type of std::atomic<T> can be atomically operated on from different threads without causing any data race. But also, there is another aspect of std::atomic<T>that is important to know in order to avoid having tricky bugs, or to improve performance of your programs. The aspect is related to memory model¹ ,especially memory ordering².

There are six memory orderings that are specified in the C++ standard: memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel and memory_order_seq_cst³. You can specify these memory orderings with atomic operation like below.

example) x.store(true, std::memory_order_relaxed);

The six models can be largely categorized into three ordering categories as below.

  • Relaxed ordering (memory_order_relaxed).
  • Acquire-release ordering (memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel)
  • Sequentially consistent ordering (memory_order_seq_cst)

In this post, I will explain about the three categories by using simple diagrams and concrete examples and hopefully it will give you enough understanding to go look into the details of each memory_order options.

Relaxed ordering

First, I will explain the relaxed ordering (std::memory_order_relaxed). Let’s see the example program below. As you can see, there are two threads (thread_1 and thread_2).

In thread_1, it is storing true to atomic object x, then storing true value to atomic object y.

In thread_2, it is checking the value of y in a while loop and repeat until it reads true. After it goes out of the loop, if the value of xis true then it prints "y == true also x == true”.

#include <atomic>
#include <thread>
#include <iostream>
std::atomic<bool> x,y;void func_1() {
x.store(true…

--

--