-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy path003_std_thread_std_atomic.cpp
More file actions
35 lines (32 loc) · 970 Bytes
/
003_std_thread_std_atomic.cpp
File metadata and controls
35 lines (32 loc) · 970 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
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
std::atomic_flag lock = ATOMIC_FLAG_INIT;
void f(int n)
{
for (int cnt = 0; cnt < 40; ++cnt) {
while (lock.test_and_set(std::memory_order_acquire)) { // acquire lock
// Since C++20, it is possible to update atomic_flag's
// value only when there is a chance to acquire the lock.
// See also: https://stackoverflow.com/questions/62318642
#if defined(__cpp_lib_atomic_flag_test)
while (lock.test(std::memory_order_relaxed)) // test lock
#endif
; // spin
}
static int out{};
std::cout << n << ((++out % 40) == 0 ? '\n' : ' ');
lock.clear(std::memory_order_release); // release lock
}
}
int main()
{
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n) {
v.emplace_back(f, n);
}
for (auto& t : v) {
t.join();
}
}