Skip to content

Instantly share code, notes, and snippets.

@senderista
Last active February 4, 2026 19:37
Show Gist options
  • Select an option

  • Save senderista/766d9ae02bf9527706f22cd456c4ba92 to your computer and use it in GitHub Desktop.

Select an option

Save senderista/766d9ae02bf9527706f22cd456c4ba92 to your computer and use it in GitHub Desktop.
Peterson's algorithm in C++11 atomics (Dmitry Vyukov)
// Peterson's algorithm in C++11 atomics
//
// Adapted from Dmitry Vyukov's example in the comments to https://bartoszmilewski.com/2008/12/01/c-atomics-and-memory-ordering/.
// For a correctness argument, see https://www.justsoftwaresolutions.co.uk/threading/petersons_lock_with_C++0x_atomics.html.
#include <atomic>
#include <immintrin.h>
constexpr size_t CACHE_LINE_SIZE = 64;
struct alignas(CACHE_LINE_SIZE)
aligned_atomic_bool { std::atomic<bool> val; };
aligned_atomic_bool flag[2];
std::atomic<int> turn = 0;
void lock(int index) {
const int other_index = 1 - index;
flag[index].val.store(true, std::memory_order_relaxed);
turn.exchange(other_index, std::memory_order_acq_rel);
while (flag[other_index].val.load(std::memory_order_acquire) &&
other_index == turn.load(std::memory_order_relaxed))
_mm_pause();
}
void unlock(int index) {
flag[index].val.store(false, std::memory_order_release);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment