| 1 | (* A lock for short sections: a thread that finds it taken tries again, |
| 2 | giving up the processor now and then. Zero is free. *) |
| 3 | module Lock; |
| 4 | import Sys; |
| 5 | |
| 6 | type Lock* = record held: INT; end; |
| 7 | |
| 8 | proc take*(l: ^Lock); |
| 9 | var tries: INT; |
| 10 | begin |
| 11 | while not CAS(ADR(l^.held), 0, 1) do |
| 12 | INC(tries); |
| 13 | if tries mod 64 = 0 then Sys.yield; end; |
| 14 | end; |
| 15 | end; |
| 16 | |
| 17 | proc give*(l: ^Lock); |
| 18 | begin |
| 19 | _ := XCHG(ADR(l^.held), 0); |
| 20 | end; |
| 21 | |
| 22 | end Lock. |