Skip to content

Instantly share code, notes, and snippets.

@kjk
Last active July 21, 2020 09:32
Show Gist options
  • Save kjk/a3be0f9c9552fff392e9567f15094160 to your computer and use it in GitHub Desktop.
Save kjk/a3be0f9c9552fff392e9567f15094160 to your computer and use it in GitHub Desktop.
#include <iostream> // std::cout
#include <atomic> // std::atomic, std::memory_order_relaxed
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment