1 -----------------------------------------------------------------------------
3 -- Module : Control.Concurrent.SampleVar
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/core/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : non-portable
13 -----------------------------------------------------------------------------
15 module Control.Concurrent.SampleVar
17 SampleVar, -- :: type _ =
19 newEmptySampleVar, -- :: IO (SampleVar a)
20 newSampleVar, -- :: a -> IO (SampleVar a)
21 emptySampleVar, -- :: SampleVar a -> IO ()
22 readSampleVar, -- :: SampleVar a -> IO a
23 writeSampleVar -- :: SampleVar a -> a -> IO ()
29 import Control.Concurrent.MVar
31 -- Sample variables are slightly different from a normal MVar:
33 -- * Reading an empty SampleVar causes the reader to block.
34 -- (same as takeMVar on empty MVar)
36 -- * Reading a filled SampleVar empties it and returns value.
39 -- * Writing to an empty SampleVar fills it with a value, and
40 -- potentially, wakes up a blocked reader (same as for putMVar on
43 -- * Writing to a filled SampleVar overwrites the current value.
44 -- (different from putMVar on full MVar.)
47 = MVar (Int, -- 1 == full
49 -- <0 no of readers blocked
52 -- Initally, a SampleVar is empty/unfilled.
54 newEmptySampleVar :: IO (SampleVar a)
55 newEmptySampleVar = do
59 newSampleVar :: a -> IO (SampleVar a)
65 emptySampleVar :: SampleVar a -> IO ()
67 (readers, var) <- takeMVar v
71 putMVar v (readers,var)
74 -- filled => make empty and grab sample
75 -- not filled => try to grab value, empty when read val.
77 readSampleVar :: SampleVar a -> IO a
78 readSampleVar svar = do
79 (readers,val) <- takeMVar svar
80 putMVar svar (readers-1,val)
84 -- filled => overwrite
85 -- not filled => fill, write val
87 writeSampleVar :: SampleVar a -> a -> IO ()
88 writeSampleVar svar v = do
89 (readers,val) <- takeMVar svar
96 putMVar svar (min 1 (readers+1), val)