CodeBlanks Logo Icon CodeBlanks

Sequential consistency

Learn sequential consistency and other memory orders.

Sequential consistency

Sequential consistency (seq_cst) is the strongest memory ordering in C++ and the default for std::atomic operations. All threads see all operations in a single consistent order.

Example: x.store(1) uses std::memory_order_seq_cst by default. This strong guarantee carries a performance cost; but the program behavior is the easiest to reason about. On high-latency or many-core systems, weaker orderings may be preferred.

Total order

seq_cst operations form a single total order across all threads. Every thread sees the same order; no contradictory observations occur. This makes the program easy to reason about.

The cost is performance: the processor must wait for all previous writes to become visible. So weaker orderings (release-acquire or relaxed) are used only where they suffice. Wrong use can lead to races or inconsistent results.

Practice Write an atomic store with seq_cst

Define a global std::atomic<int> x{0};. In main write x.store(5); (default seq_cst) and std::cout << x.load();.

Starter code

main.cpp
#include <iostream>
#include <atomic>

// Define the x atomic here

int main() {
    // Store a value and load it
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <atomic>

std::atomic<int> x{0};

int main() {
    x.store(5);
    std::cout << x.load();
    return 0;
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each ordering to its strength

Term Meaning
memory_order_seq_cst Default, strongest
memory_order_relaxed Weakest
memory_order_acquire Read side
memory_order_release Write side

2 Complete the seq_cst store

Question
x.store(1, std::memory_order_____);
Answer
x.store(1, std::memory_order_seq_cst);

Explanation: seq_cst is the default and strongest ordering.

3 What is the default memory order for std::atomic operations?

main.cpp
x.store(1);  // default
  • memory_order_acquire
  • memory_order_relaxed
  • memory_order_seq_cst Correct answer
  • memory_order_release

Explanation: seq_cst is the default ordering; it gives the strongest guarantee.

All lessons in Expert