public member function
<atomic>

std::atomic_flag::atomic_flag

atomic_flag() noexcept = default;atomic_flag (const atomic_flag&T) = delete;
Construct atomic flag
Constructs an atomic_flag object.

The atomic_flag is in an unspecified state on construction (either set or clear), unless it is explicitly initialized to ATOMIC_FLAG_INIT.

Whether ATOMIC_FLAG_INIT initialization is achieved by simply calling the default constructor or by other means, depends on the particular library implementation.

atomic_flag values cannot be copied/moved (constructor and assigment deleted).

Parameters

ATOMIC_FLAG_INIT
If the object is initialized with this macro, it is guaranteed to be constructed with a clear state.

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
// constructing atomics: atomic<bool> vs atomic_flag
#include <iostream>       // std::cout
#include <atomic>         // std::atomic, std::atomic_flag, ATOMIC_FLAG_INIT
#include <thread>         // std::thread, std::this_thread::yield
#include <vector>         // std::vector

std::atomic<bool> ready (false);               // can be checked without being set
std::atomic_flag winner = ATOMIC_FLAG_INIT;    // always set when checked

void count1m (int id) {
  while (!ready) { std::this_thread::yield(); }      // wait for the ready signal
  for (int i=0; i<1000000; ++i) {}                   // go!, count to 1 million
  if (!winner.test_and_set()) { std::cout << "thread #" << id << " won!\n"; }
};

int main ()
{
  std::vector<std::thread> threads;
  std::cout << "spawning 10 threads that count to 1 million...\n";
  for (int i=1; i<=10; ++i) threads.push_back(std::thread(count1m,i));
  ready = true;
  for (auto& th : threads) th.join();

  return 0;
}

Possible output:
spawning 10 threads that count to 1 million...
thread #6 won!


Data races

No data races (atomic operation).

Exception safety

No-throw guarantee: never throws exceptions.

See also