-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatomic_StoreLoadExchanceCAS.cpp
More file actions
54 lines (50 loc) · 1.25 KB
/
atomic_StoreLoadExchanceCAS.cpp
File metadata and controls
54 lines (50 loc) · 1.25 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//+= or ++
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
#include <mutex>
using namespace std;
int main() {
atomic<int> x{ 10 };//+= will also be atomic
/*
// Different ways to initialize an atomic variable
atomic<int> x( 10 ) -> compiles
atomic<int> x{ 10 } -> compiles
atomic<int> x = { 10 } -> compiles
atomic<int> x = 0 -> doesn't compile
atomic<int> x; x = 0; -> compiles
*/
cout << x << endl; //10
int y = x.load();
cout << y << endl; //10
y += 10;
x.store(y);
cout << "After Store" << endl;
cout << x << endl; //20
cout << y << endl; //20
y = 100;
int z = x.exchange(y);
cout << "y = 100 \nAfter Exchange. . ." << endl;
cout << x << endl; //100
cout << y << endl; //100
cout << z << endl; //20
bool success = x.compare_exchange_strong(y, z);
/*
if x == y, make x = z and return true
else y = x and return false
*/
cout << "After compare_exchange_strong" << endl;
cout << x << endl; // 20
cout << y << endl; // 100
cout << z << endl; // 20
cout << success << endl; // 1
/*
atomic<int> z{ 0 };
int z0 = z;
while(!z.compare_exchange_strong(z0, z0 + 1))
*/
return 0;
}
// Using the special operations is preferred when you want to add memory order detail to an operation
// More on memory order later