public member function
<atomic>

std::atomic::atomic

default (1)
          atomic() noexcept = default;
initialization (2)
constexpr atomic (T val) noexcept;
copy [deleted] (3)
          atomic (const atomic&) = delete;
Construct atomic
Constructs an atomic object:

(1) default constructor
Leaves the atomic object in an uninitialized state.
An uninitialized atomic object may later be initialized by calling atomic_init.
(2) initialization constructor
Initializes the object with val.
(3) copy construction
Deleted (atomic objects cannot be copied/moved).

Parameters

val
Value to initialize the contained object with.
T is atomic's template parameter (the type of the contained value).

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
#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);
std::atomic_flag winner = ATOMIC_FLAG_INIT;

void count1m (int id) {
  while (!ready) { std::this_thread::yield(); }      // wait for the ready signal
  for (volatile 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 #7 won!

Data races

The construction itself is not atomic: Accessing the object while being constructed may initiate a data race.

Exception safety

No-throw guarantee: never throws exceptions.

See also