| 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. *) |
| 5 | module Lock; |
| 6 | import Sys, Rt; |
| 7 | |
| 8 | (* A lock, free when zeroed. *) |
| 9 | type Lock* = record held: INT; end; |
| 10 | |
| 11 | (* Takes l, waiting while another thread holds it. *) |
| 12 | proc take*(var l: Lock); |
| 13 | var tries: INT; |
| 14 | begin |
| 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; |
| 20 | end; |
| 21 | |
| 22 | (* Gives up l, which the caller holds. *) |
| 23 | proc give*(var l: Lock); |
| 24 | begin |
| 25 | _ := XCHG(l.held, 0); |
| 26 | end; |
| 27 | |
| 28 | (* The module's test, in one thread: taken, given, taken again. *) |
| 29 | proc main*; |
| 30 | var l: Lock; |
| 31 | begin |
| 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; |
| 38 | end; |
| 39 | |
| 40 | end Lock. |