std::atomic<T>
suggest changeThe std::atomic<T> template provides indivisible operations on values shared between threads. It supports suitable trivially copyable types, while specializations for integral and pointer types provide additional operations such as incrementing.
Conflicting non-atomic accesses to the same object from different threads cause a data race and undefined behavior unless synchronization orders those accesses.
Atomic operations prevent data races on the atomic object and can establish ordering between other memory accesses. The default sequentially consistent ordering is often the easiest to reason about; weaker memory orders require care.
Example using std::atomic_int:
#include <iostream> // std::cout
#include <atomic> // std::atomic
#include <thread> // std::thread
std::atomic_int foo (0);
void set_foo(int x) {
foo.store(x); // set value atomically
}
void print_foo() {
int x;
do {
x = foo.load(); // get value atomically
} while (x==0);
std::cout << "foo: " << x << '\n';
}
int main ()
{
std::thread first (print_foo);
std::thread second (set_foo,10);
first.join();
second.join();
return 0;
}
foo: 10
std::atomic<T> specialization in standard library
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents