2 % (c) The GRASP/AQUA Project, Glasgow University, 1995
4 \section[SampleVar]{Sample variables}
6 Sample variables are slightly different from a normal @MVar@:
9 \item Reading an empty @SampleVar@ causes the reader to block.
10 (same as @takeMVar@ on empty @MVar@)
11 \item Reading a filled @SampleVar@ empties it and returns value.
13 \item Writing to an empty @SampleVar@ fills it with a value, and
14 potentially, wakes up a blocked reader (same as for @putMVar@ on empty @MVar@).
15 \item Writing to a filled @SampleVar@ overwrites the current value.
16 (different from @putMVar@ on full @MVar@.)
22 SampleVar, --:: type _ =
24 newEmptySampleVar, --:: IO (SampleVar a)
25 newSampleVar, --:: a -> IO (SampleVar a)
26 emptySampleVar, --:: SampleVar a -> IO ()
27 readSampleVar, --:: SampleVar a -> IO a
28 writeSampleVar --:: SampleVar a -> a -> IO ()
36 = MVar (Int, -- 1 == full
38 -- <0 no of readers blocked
41 -- Initally, a @SampleVar@ is empty/unfilled.
43 newEmptySampleVar :: IO (SampleVar a)
44 newEmptySampleVar = do
48 newSampleVar :: a -> IO (SampleVar a)
54 emptySampleVar :: SampleVar a -> IO ()
56 (readers, var) <- takeMVar v
60 putMVar v (readers,var)
63 -- filled => make empty and grab sample
64 -- not filled => try to grab value, empty when read val.
66 readSampleVar :: SampleVar a -> IO a
67 readSampleVar svar = do
68 (readers,val) <- takeMVar svar
69 putMVar svar (readers-1,val)
73 -- filled => overwrite
74 -- not filled => fill, write val
76 writeSampleVar :: SampleVar a -> a -> IO ()
77 writeSampleVar svar v = do
78 (readers,val) <- takeMVar svar
85 putMVar svar (min 1 (readers+1), val)