| 1 | (* A value of type T together with the lock that guards it, so that |
| 2 | sharing a container between threads is hard to do wrong: the value |
| 3 | can be reached only through with, which holds the lock while it |
| 4 | runs. |
| 5 | |
| 6 | A Guarded is ready as it is, with a zero value and the lock free; |
| 7 | with can set any other. The lock is a Thread.Mutex, which sleeps |
| 8 | while it waits, so p may take its time. p must not call with on the |
| 9 | same Guarded, which would wait for itself, and must not keep a |
| 10 | pointer into x past its return. |
| 11 | |
| 12 | It depends on Thread. It leaves out reading the value without the |
| 13 | lock, a try-lock and a lock shared by several values: a program |
| 14 | that wants those uses Thread.Mutex itself. *) |
| 15 | module Guarded(T); |
| 16 | import Thread; |
| 17 | |
| 18 | type |
| 19 | Guarded* = record |
| 20 | lock: Thread.Mutex; (* held while the value is used *) |
| 21 | value: T; (* what the lock guards *) |
| 22 | end; |
| 23 | |
| 24 | (* Runs p on the value, holding the lock, so that no other thread uses |
| 25 | it at the same time. *) |
| 26 | proc with*(var g: Guarded; p: proc(var x: T)); |
| 27 | begin |
| 28 | Thread.lock(g.lock); |
| 29 | p(g.value); |
| 30 | Thread.unlock(g.lock); |
| 31 | end; |
| 32 | |
| 33 | end Guarded. |