Reference

<atomic>

class
<atomic>

std::atomic_flag

struct atomic_flag;
Atomic flag
Atomic flags are boolean atomic objects that support two operations: test-and-set and clear .

Atomic flags are lock-free (this is the only type guaranteed to be lock-free on all library implementations).

Member functions

(constructor)
Construct atomic flag (public member function)
test_and_set
Test and set flag (public member function)
clear
Clear flag (public member function)
operator= is deleted (non-copyable/moveable).

Example

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
// using atomic_flag as a lock
#include <iostream> // std::cout
#include <atomic> // std::atomic_flag
#include <thread> // std::thread
#include <vector> // std::vector
#include <sstream> // std::stringstream
std::atomic_flag lock_stream = ATOMIC_FLAG_INIT;
std::stringstream stream;
void append_number(int x) {
 while (lock_stream.test_and_set()) {}
 stream << "thread #" << x << '\n';
 lock_stream.clear();
}
int main ()
{
 std::vector<std::thread> threads;
 for (int i=1; i<=10; ++i) threads.push_back(std::thread(append_number,i));
 for (auto& th : threads) th.join();
 std::cout << stream.str();
 return 0;
}

Possible output (order of lines may vary):
thread #1
thread #2
thread #3
thread #4
thread #5
thread #6
thread #7
thread #8
thread #9
thread #10

AltStyle によって変換されたページ (->オリジナル) /