mirror of
https://github.com/changkun/modern-cpp-tutorial.git
synced 2025-12-17 12:44:40 +03:00
see #2: update std::atomic and memory model
This commit is contained in:
21
code/7/7.8.relaxed.cpp
Normal file
21
code/7/7.8.relaxed.cpp
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user