Last active
February 3, 2023 02:38
-
-
Save mkckr0/cf37df2efc75dde8c844b34252e5e687 to your computer and use it in GitHub Desktop.
write_x_and_read_y.c 的 C++ 版本
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> | |
#include <thread> | |
#include <atomic> | |
#include <chrono> | |
using namespace std::literals; | |
std::atomic_int flag{ 0x00 }; | |
std::atomic_int x{ 0 }, y{ 0 }; | |
void f1() | |
{ | |
while (true) { | |
while (!(flag & 0b10)); | |
x.store(11, std::memory_order_relaxed); | |
// std::atomic_thread_fence(std::memory_order_seq_cst); | |
int v = y.load(std::memory_order_relaxed); | |
printf("%i ", v); | |
flag.fetch_and(0b01); | |
} | |
} | |
void f2() | |
{ | |
while (true) { | |
while (!(flag & 0b01)); | |
y.store(22, std::memory_order_relaxed); | |
// std::atomic_thread_fence(std::memory_order_seq_cst); | |
int v = x.load(std::memory_order_relaxed); | |
printf("%i ", v); | |
flag.fetch_and(0b10); | |
} | |
} | |
int main() | |
{ | |
std::thread t1(f1), t2(f2); | |
while (true) { | |
x = 0, y = 0; | |
flag = 0b11; | |
// std::this_thread::sleep_for(1ms); | |
while (flag); | |
printf("\n"); | |
fflush(stdout); | |
} | |
t1.join(); | |
t2.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-O2
./write_x_read_y.out | head -n10000 | sort | uniq -c