Skip to content

Instantly share code, notes, and snippets.

@kprotty
Last active October 13, 2026 22:05
Show Gist options
  • Select an option

  • Save kprotty/d96312c475218affe2dfd4dab3db194c to your computer and use it in GitHub Desktop.

Select an option

Save kprotty/d96312c475218affe2dfd4dab3db194c to your computer and use it in GitHub Desktop.

API

const Coherency = enum {
  // writes have defined order across threads, reads observe some write
  atomic,
  // happens atomically, but writes dont need to have a defined order across threads
  unordered,
  // need not be atomic: on data-race, produces an unspecified value instead of UB
  racy,
  // not atomic. data-race is UB
  normal
};

// compile-time dependency token between atomic operations
const Token = struct{};

// Returns a token that represents a dependency on all past memory operations on this thread.
fn all_previous() Token {
  ...
}

// Forces all future memory operations on this thread to depend on the given token.
fn all_subsequent(dep: Token) {
  ...
}

// Merges a set of dependency tokens into one
fn join(tokens: []const Token) Token {
  ...
}

// Reads some value from the ptr using the coherence while depending on a token. 
// Returns the loaded value & a token representing a dependency on this load.
fn load(comptime co: Coherency, ptr: anytype, dep: ?Token) struct{ @TypeOf(ptr.*), Token } {
  ...
}

// Writes the value to the ptr using the coherence while depending on a token.
// Returns a token representing a dependency on this store.
fn store(comptime co: Coherency, ptr: anytype, val: @TypeOf(ptr.*), dep: ?Token) Token {
  ...
}

const RmwOp = enum { Xchg, Add, Sub, And, Or, Xor, Nand, Min, Max };

// Atomically reads the old value from the ptr, does the modification defined in RwmOp, writes the modified value to ptr, and returns old value.
// It does this all while depending on a token, and returning its own token dependency.
fn rmw(ptr: anytype, comptime op: RmwOp, val: @TypeOf(ptr.*), dep: ?Token) struct{ @TypeOf(ptr.*), Token } {
  ...
}

// Atomically reads the value at ptr, checks if the value == cmp, if so writes xchg and returns null, if not returns the read value.
// Also returns a token representing a dependency on either the xchg-write for success or the value read on failure.
fn cmpxchg(ptr: anytype, cmp: @TypeOf(ptr.*), xchg: @TypeOf(ptr.*), dep: ?Token) struct{ ?@TypeOf(ptr.*), Token } {
  ...
}

Patterns

// acquire load
value, token = load(.atomic, ptr, null)
all_subsequent(token)

// release store
token = all_previous()
_ = store(.atomic, ptr, val, token)

// seq_cst fence
all_subsequent(all_previous())

// consume load
v, tok = load(.atomic, ptr, null)
if validate(v):
  v = load(.normal, &other[v], tok)

// store-load barrier
tok = store(.atomic, ptr, val, null)
v, tok = load(.atomic, ptr, tok)

// multi release-fence
t1 = store(.atomic, ptr1, val1, null)
t2 = store(.atomic, ptr2, val2, null)
t3 = store(.atomic, ptr3, val3, null)
tok = join(&.{ t1, t2, t3 })
all_subsequent(tok)

Algorithms

type RefCount:
  count: usize = 1
  
  clone():
    _ = rmw(.atomic, .Add, &count, 1, null)
    
  drop(dep: Token = all_previous()):
    c, tok = rmw(.atomic, .Sub, &count, 1, dep)
    if c == 1:
      destructor(tok)
type SeqLock(T):
  state: u64 = 0
  value: T
  
  read() -> T:
    loop:
      s1, tok = load(.atomic, &state, null)
      if s1 & 1 > 0: continue
      val, tok = load(.racy, &value, tok)
      s2, tok = load(.atomic, &state, tok)
      if s1 == s2: return val

  write(new: T):
    s = load(.normal, &state, null)
    tok = store(.atomic, &state, s | 1, null)
    tok = store(.racy, &value, new, tok)
    _ = store(.atomic, &state, s +% 2, tok)
type Mutex:
  state: enum(u32){ unlocked, locked, contended } = .unlocked
  
  c11_lock(): all_subsequent(lock())
  lock() -> Token:
    // fast path
    s, tok = cmpxchg(&state, .unlocked, .locked, null)
    _ = s orelse return tok // success=null, returning cmpxchg's store token
    
    // slow path
    loop:
      s, tok = rmw(&state, .Xchg, .contended, null)
      if s == .unlocked: return tok
      futex_wait(&state, .contended)
  
  c11_unlock(): unlock(all_previous())
  unlock(dep: Token):
    // fast path
    s, tok = rmw(&state, .Xchg, .unlocked, dep)
    if s == .contended: // slow path
      futex_wake(&state, 1)
type RingBuf(T, n):
  head: u64 align(128) = 0
  tail: u64 align(128) = 0
  array: [n]T
  
  read() -> ?T:
    h, _ = load(.normal, &head, null)
    t, tok = load(.atomic, &tail, null)
    if h == t: return null
    
    val, tok = load(.normal, &array[h % n], tok)
    _ = store(.atomic, &head, h +% 1, tok)
    return val
  
  write(new: T) -> bool:
    t, _ = load(.normal, &tail, null)
    h, tok = load(.atomic, &head, null)
    if t -% h == n: return false

    tok = store(.normal, &array[t % n], new, tok)
    _ = store(.atomic, &tail, t +% 1, tok)
    return true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment