(* A lock for short sections of code: a word set to 1, atomically, by the thread that takes it. A thread that finds it taken tries again, giving up the processor now and then. It works with C's threads and with Thread's alike; Thread.Mutex is the one that sleeps. *) module Lock; import Sys, Rt; (* A lock, free when zeroed. *) type Lock* = record held: INT; end; (* Takes l, waiting while another thread holds it. *) proc take*(var l: Lock); var tries: INT; begin tries := 0; while not CAS(l.held, 0, 1) do INC(tries); if tries = 64 then Sys.yield; tries := 0; end; end; end; (* Gives up l, which the caller holds. *) proc give*(var l: Lock); begin _ := XCHG(l.held, 0); end; (* The module's test, in one thread: taken, given, taken again. *) proc main*; var l: Lock; begin take(l); if l.held # 1 then Rt.stop("Lock.take"); end; give(l); take(l); give(l); if l.held # 0 then Rt.stop("Lock.give"); end; end; end Lock.