see #2: update std::atomic and memory model

This commit is contained in:
Changkun Ou
2019-07-18 17:22:23 +02:00
parent 5e9c33002a
commit 6062a58161
6 changed files with 223 additions and 8 deletions

19
code/7/7.6.atomic.cpp Normal file
View File

@@ -0,0 +1,19 @@
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> count = {0};
int main() {
std::thread t1([](){
count.fetch_add(1);
});
std::thread t2([](){
count++; // identical to fetch_add
count += 1; // identical to fetch_add
});
t1.join();
t2.join();
std::cout << count << std::endl;
return 0;
}

View File

@@ -0,0 +1,12 @@
#include <atomic>
#include <iostream>
struct A {
float x;
int y;
long long z;
};
std::atomic<A> a;
std::cout << std::boolalpha << a.is_lock_free() << std::endl;
return 0;
}

21
code/7/7.8.relaxed.cpp Normal file
View File

@@ -0,0 +1,21 @@
#include <atomic>
#include <thread>
#include <vector>
#include <iostream>
std::atomic<int> counter = {0};
int main() {
std::vector<std::thread> vt;
for (int i = 0; i < 100; ++i) {
vt.emplace_back([](){
counter.fetch_add(1, std::memory_order_relaxed);
});
}
for (auto& t : vt) {
t.join();
}
std::cout << "current counter:" << counter << std::endl;
return 0;
}