Last active
December 6, 2022 05:22
-
-
Save hisui/712d850a6bb40639c6cc1cb48dd79544 to your computer and use it in GitHub Desktop.
memory order SeqCst demo
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 <thread> | |
#include <atomic> | |
#include <assert.h> | |
using namespace std; | |
static atomic<int> a = 0; | |
static atomic<int> b = 0; | |
static atomic<int> A = 0; | |
static atomic<int> B = 0; | |
constexpr auto w_order = memory_order_seq_cst; | |
constexpr auto r_order = memory_order_seq_cst; | |
static void threadX() | |
{ | |
a.store(1, w_order); | |
A = b.load(r_order); | |
} | |
static void threadY() | |
{ | |
b.store(1, w_order); | |
B = a.load(r_order); | |
} | |
int main() | |
{ | |
for (int i = 0; i < 10'000; ++i) { | |
a = b = A = B = 0; | |
auto x = thread(threadX); | |
auto y = thread(threadY); | |
x.join(); | |
y.join(); | |
// fprintf(stderr, "A:%d B:%d\n", A.load(), B.load()); | |
assert(!(A == 0 && B == 0)); // fails if any of w/r orders are other than SeqCst. | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment