Skip to content

Instantly share code, notes, and snippets.

@ed-aka-yaboi
Created March 23, 2026 16:31
Show Gist options
  • Select an option

  • Save ed-aka-yaboi/7708058be3139159fc5086ef6af4f573 to your computer and use it in GitHub Desktop.

Select an option

Save ed-aka-yaboi/7708058be3139159fc5086ef6af4f573 to your computer and use it in GitHub Desktop.
lockfree knowledge check
  1. How is the following code broken?
  2. Why does it work on x86? Why not on arm?
#include "relacy/context.hpp"
#include "relacy/memory_order.hpp"
#include <relacy/relacy.hpp>

static constexpr size_t THREADS = 2;
static constexpr int ITERS = 4;

struct Test : rl::test_suite<Test, THREADS> {
  rl::atomic<bool> flag{false};
  rl::atomic<int> data{0};

  void thread(unsigned thread_id) {
    if (thread_id == 0) {
      for (int i = 0; i < ITERS; ++i) {
        if (!flag.load(rl::memory_order_relaxed)) {
          data.store(42, rl::memory_order_relaxed);
          flag.store(true, rl::memory_order_relaxed);
        } else {
          flag.store(false, rl::memory_order_relaxed);
          data.store(0, rl::memory_order_relaxed);
        }
        rl::yield(1, RL_INFO);
      }
    } else {
      for (int i = 0; i < ITERS; ++i) {
        if (flag.load(rl::memory_order_acq_rel)) {
          RL_ASSERT(data.load(rl::memory_order_relaxed) == 42);
        }
        rl::yield(1, RL_INFO);
      }
    }
  }
};

int main() { rl::simulate<Test>(); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment