Last active
July 21, 2020 09:32
-
-
Save kjk/a3be0f9c9552fff392e9567f15094160 to your computer and use it in GitHub Desktop.
Example for https://essential-cpp.programming-books.io/stdatomic-ede1fd1200134e8ba92d109c2ef39c10 (made with https://codeeval.dev)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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