Sequential Consistency

Familiarize yourself with sequential consistency in C++.

We'll cover the following...

Let us dive deeper into sequential consistency. The key for sequential consistency is that all operations on all threads obey a universal clock. This universal clock makes it quite intuitive to think about it.

The intuitiveness of the sequential consistency comes with a price. The downside is that the system has to do a lot of work to keep the threads in sync. The following program synchronizes the producer and the consumer thread with the help of sequential consistency.

Press + to interact
// producerConsumer.cpp
#include <atomic>
#include <iostream>
#include <string>
#include <thread>
std::string work;
std::atomic<bool> ready(false);
void consumer(){
while(!ready.load()){}
std::cout<< work << std::endl;
}
void producer(){
work= "done";
ready=true;
}
int main(){
std::thread prod(producer);
std::thread con(consumer);
prod.join();
con.join();
}

The output of the program is not very exciting. Because of sequential consistency, the program execution is totally deterministic; its output is always “done”. The graphic depicts the sequence of operations. The consumer thread waits in the while-loop until the atomic variable ...