raz / lib / Lock.raz

40 lines · 988 B · raw · history · last change e0d008cd

1(* A lock for short sections of code: a word set to 1, atomically, by
2 the thread that takes it. A thread that finds it taken tries again,
3 giving up the processor now and then. It works with C's threads and
4 with Thread's alike; Thread.Mutex is the one that sleeps. *)
5module Lock;
6import Sys, Rt;
7
8(* A lock, free when zeroed. *)
9type Lock* = record held: INT; end;
10
11(* Takes l, waiting while another thread holds it. *)
12proc take*(var l: Lock);
13var tries: INT;
14begin
15 tries := 0;
16 while not CAS(l.held, 0, 1) do
17 INC(tries);
18 if tries = 64 then Sys.yield; tries := 0; end;
19 end;
20end;
21
22(* Gives up l, which the caller holds. *)
23proc give*(var l: Lock);
24begin
25 _ := XCHG(l.held, 0);
26end;
27
28(* The module's test, in one thread: taken, given, taken again. *)
29proc main*;
30var l: Lock;
31begin
32 take(l);
33 if l.held # 1 then Rt.stop("Lock.take"); end;
34 give(l);
35 take(l);
36 give(l);
37 if l.held # 0 then Rt.stop("Lock.give"); end;
38end;
39
40end Lock.