1 -----------------------------------------------------------------------------
3 -- Module : Control.Concurrent.SampleVar
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : non-portable (concurrency)
13 -----------------------------------------------------------------------------
15 module Control.Concurrent.SampleVar
18 SampleVar, -- :: type _ =
20 newEmptySampleVar, -- :: IO (SampleVar a)
21 newSampleVar, -- :: a -> IO (SampleVar a)
22 emptySampleVar, -- :: SampleVar a -> IO ()
23 readSampleVar, -- :: SampleVar a -> IO a
24 writeSampleVar -- :: SampleVar a -> a -> IO ()
30 import Control.Concurrent.MVar
33 -- Sample variables are slightly different from a normal 'MVar':
35 -- * Reading an empty 'SampleVar' causes the reader to block.
36 -- (same as 'takeMVar' on empty 'MVar')
38 -- * Reading a filled 'SampleVar' empties it and returns value.
39 -- (same as 'takeMVar')
41 -- * Writing to an empty 'SampleVar' fills it with a value, and
42 -- potentially, wakes up a blocked reader (same as for 'putMVar' on
45 -- * Writing to a filled 'SampleVar' overwrites the current value.
46 -- (different from 'putMVar' on full 'MVar'.)
49 = MVar (Int, -- 1 == full
51 -- <0 no of readers blocked
54 -- |Build a new, empty, 'SampleVar'
55 newEmptySampleVar :: IO (SampleVar a)
56 newEmptySampleVar = do
60 -- |Build a 'SampleVar' with an initial value.
61 newSampleVar :: a -> IO (SampleVar a)
67 -- |If the SampleVar is full, leave it empty. Otherwise, do nothing.
68 emptySampleVar :: SampleVar a -> IO ()
70 (readers, var) <- takeMVar v
74 putMVar v (readers,var)
76 -- |Wait for a value to become available, then take it and return.
77 readSampleVar :: SampleVar a -> IO a
78 readSampleVar svar = do
80 -- filled => make empty and grab sample
81 -- not filled => try to grab value, empty when read val.
83 (readers,val) <- takeMVar svar
84 putMVar svar (readers-1,val)
87 -- |Write a value into the 'SampleVar', overwriting any previous value that
89 writeSampleVar :: SampleVar a -> a -> IO ()
90 writeSampleVar svar v = do
92 -- filled => overwrite
93 -- not filled => fill, write val
95 (readers,val) <- takeMVar svar
102 putMVar svar (min 1 (readers+1), val)