Search⌘ K

Sequential Consistency

Explore the concept of sequential consistency in C++ concurrency. Understand how it enforces a universal order of operations across threads, ensuring deterministic program behavior. This lesson explains synchronization between threads, atomic operations, and how the happens-before relationship maintains consistency in concurrent execution.

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.

C++
// 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 ...