Skip to content

Instantly share code, notes, and snippets.

@mkckr0
Last active February 3, 2023 02:38
Show Gist options
  • Save mkckr0/cf37df2efc75dde8c844b34252e5e687 to your computer and use it in GitHub Desktop.
Save mkckr0/cf37df2efc75dde8c844b34252e5e687 to your computer and use it in GitHub Desktop.
write_x_and_read_y.c 的 C++ 版本
#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();
}
@mkckr0
Copy link
Author

mkckr0 commented Jul 9, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment