-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader_writer5.cpp
More file actions
35 lines (27 loc) · 870 Bytes
/
reader_writer5.cpp
File metadata and controls
35 lines (27 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Memory Model - Sequential Consistency, the ordering of execution in the thread will be consistent and same. Universal order of instructions.
//Using atomic variables with acquire release semantics
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <atomic>
using namespace std;
int x; // Only atomic operations allowed
atomic<int> y;
void reading() {
cout << "x: " << x << endl; // x is not atomic, it can be read from while it is being written
cout << "y: " << y.load(memory_order_relaxed) << endl;
}
void writing() {
y.store(2000, memory_order_relaxed);
x = 11;
}
int main() {
y.store(0);
// For atomic variables the order of threads is what the order they are executed in
thread writer = thread(writing);
thread reader = thread(reading);
writer.join();
reader.join();
return 0;
}