#include <atomic>
#include <barrier>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <thread>

constexpr size_t iterations = 10'000'000;

template <typename F>
std::thread run_iterations(std::barrier<>& rendezvous, F f) {
    return std::thread([&rendezvous, f] {
        for (size_t i = 0; i < iterations; ++i) {
            rendezvous.arrive_and_wait();  // wait for everyone to be ready
            f();
            rendezvous.arrive_and_wait();  // wait for everyone to finish
        }
    });
}

int main() {
    // Ensure the atomics don't share cache lines 
    alignas(128) std::atomic<int> x;
    alignas(128) std::atomic<int> y;
    bool x_set_before_y;
    bool y_set_before_x;

    std::barrier<> rendezvous {5};  // 4 worker threads + main

    std::thread write_x = run_iterations(rendezvous,
        [&] {
            x.store(1, std::memory_order_relaxed);
            // x.store(1, std::memory_order_release);
        }
    );
    std::thread write_y = run_iterations(rendezvous,
        [&] {
            y.store(1, std::memory_order_relaxed);
            // y.store(1, std::memory_order_release);
        }
    );
    std::thread read_x_then_y = run_iterations(rendezvous,
        [&] {
            while (x.load(std::memory_order_relaxed) == 0)
            // while (x.load(std::memory_order_acquire) == 0)
                ;
            if (y.load(std::memory_order_relaxed) == 0)
            // if (y.load(std::memory_order_acquire) == 0)
                x_set_before_y = true;
        }
    );
    std::thread read_y_then_x = run_iterations(rendezvous,
        [&] {
            while (y.load(std::memory_order_relaxed) == 0)
            // while (y.load(std::memory_order_acquire) == 0)
                ;
            if (x.load(std::memory_order_relaxed) == 0)
            // if (x.load(std::memory_order_acquire) == 0)
                y_set_before_x = true;
        }
    );

    for (size_t i = 0; i < iterations; ++i) {
        x = 0;
        y = 0;
        x_set_before_y = false;
        y_set_before_x = false;

        rendezvous.arrive_and_wait();  // wait for workers to be ready

        rendezvous.arrive_and_wait();  // wait for workers to finish

        assert(!(x_set_before_y && y_set_before_x));
    }

    write_x.join();
    write_y.join();
    read_x_then_y.join();
    read_y_then_x.join();
}

// TODO: The assert passes anyway because arm64 is multi-copy atomic: a store
// becomes visible to all other cores at once. Each reader's two ldapr loads are
// ordered, so c and d can't see x and y set in opposite orders. The extra
// seq_cst guarantee, a single total order that also covers store→load
// reordering, isn't needed for this test because no thread does a store
// followed by a load.  The C++ memory model still allows this outcome with
// release/acquire, and POWER can exhibit it. So a pass on this machine doesn't
// prove the code is correct.