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)
68 -- |If the SampleVar is full, leave it empty. Otherwise, do nothing.
69 emptySampleVar :: SampleVar a -> IO ()
71 (readers, var) <- takeMVar v
72 if readers > 0 then do
76 putMVar v (readers,var)
78 -- |Wait for a value to become available, then take it and return.
79 readSampleVar :: SampleVar a -> IO a
80 readSampleVar svar = do
82 -- filled => make empty and grab sample
83 -- not filled => try to grab value, empty when read val.
85 (readers,val) <- takeMVar svar
86 putMVar svar (readers-1,val)
89 -- |Write a value into the 'SampleVar', overwriting any previous value that
91 writeSampleVar :: SampleVar a -> a -> IO ()
92 writeSampleVar svar v = do
94 -- filled => overwrite
95 -- not filled => fill, write val
97 (readers,val) <- takeMVar svar
104 putMVar svar (min 1 (readers+1), val)
106 -- | Returns 'True' if the 'SampleVar' is currently empty.
108 -- Note that this function is only useful if you know that no other
109 -- threads can be modifying the state of the 'SampleVar', because
110 -- otherwise the state of the 'SampleVar' may have changed by the time
111 -- you see the result of 'isEmptySampleVar'.
113 isEmptySampleVar :: SampleVar a -> IO Bool
114 isEmptySampleVar svar = do
115 (readers,val) <- readMVar svar
116 return (readers == 0)