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 ()
25 isEmptySampleVar, -- :: SampleVar a -> IO Bool
31 import Control.Concurrent.MVar
34 -- Sample variables are slightly different from a normal 'MVar':
36 -- * Reading an empty 'SampleVar' causes the reader to block.
37 -- (same as 'takeMVar' on empty 'MVar')
39 -- * Reading a filled 'SampleVar' empties it and returns value.
40 -- (same as 'takeMVar')
42 -- * Writing to an empty 'SampleVar' fills it with a value, and
43 -- potentially, wakes up a blocked reader (same as for 'putMVar' on
46 -- * Writing to a filled 'SampleVar' overwrites the current value.
47 -- (different from 'putMVar' on full 'MVar'.)
50 = MVar (Int, -- 1 == full
52 -- <0 no of readers blocked
55 -- |Build a new, empty, 'SampleVar'
56 newEmptySampleVar :: IO (SampleVar a)
57 newEmptySampleVar = do
61 -- |Build a 'SampleVar' with an initial value.
62 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
71 if readers > 0 then do
75 putMVar v (readers,var)
77 -- |Wait for a value to become available, then take it and return.
78 readSampleVar :: SampleVar a -> IO a
79 readSampleVar svar = do
81 -- filled => make empty and grab sample
82 -- not filled => try to grab value, empty when read val.
84 (readers,val) <- takeMVar svar
85 putMVar svar (readers-1,val)
88 -- |Write a value into the 'SampleVar', overwriting any previous value that
90 writeSampleVar :: SampleVar a -> a -> IO ()
91 writeSampleVar svar v = do
93 -- filled => overwrite
94 -- not filled => fill, write val
96 (readers,val) <- takeMVar svar
103 putMVar svar (min 1 (readers+1), val)
105 -- | Returns 'True' if the 'SampleVar' is currently empty.
107 -- Note that this function is only useful if you know that no other
108 -- threads can be modifying the state of the 'SampleVar', because
109 -- otherwise the state of the 'SampleVar' may have changed by the time
110 -- you see the result of 'isEmptySampleVar'.
112 isEmptySampleVar :: SampleVar a -> IO Bool
113 isEmptySampleVar svar = do
114 (readers, _) <- readMVar svar
115 return (readers == 0)