...

/

CppMem: Atomics with Sequential Consistency

CppMem: Atomics with Sequential Consistency

This lesson gives an overview of atomics with sequential consistency used in the context of CppMem.

If you don’t specify the memory model, sequential consistency will be applied. Sequential consistency guarantees two properties: each thread executes its instructions in source code order, and all threads follow the same global order. Here is the optimized version of the program using atomics.

Press + to interact
// ongoingOptimisationSequentialConsistency.cpp
#include <atomic>
#include <iostream>
#include <thread>
std::atomic<int> x{0};
std::atomic<int> y{0};
void writing(){
x.store(2000);
y.store(11);
}
void reading(){
std::cout << y.load() << " ";
std::cout << x.load() << std::endl;
}
int main(){
std::thread thread1(writing);
std::thread thread2(reading);
thread1.join();
thread2.join();
};

Let’s analyze the program. The program is data race free because x and y are atomics. Therefore, only one question is left to answer: What values are possible for x and y? The question is easy to answer. Thanks to the sequential consistency, all threads have to follow the same global order.

It holds true:

  • x.store(2000); happens-before y.store(11);
  • std::cout << y.load() << " "; happens-before std::cout << x.load() << std::endl;

Hence ...

Access this course and 1400+ top-rated courses and projects.