[project @ 2002-05-10 13:17:27 by simonmar]
[ghc-base.git] / Control / Concurrent / QSemN.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Control.Concurrent.QSemN
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable (concurrency)
10 --
11 -- Quantity semaphores in which each thread may wait for an arbitrary
12 -- \"amount\".
13 --
14 -----------------------------------------------------------------------------
15
16 module Control.Concurrent.QSemN
17         (  -- * General Quantity Semaphores
18           QSemN,        -- abstract
19           newQSemN,     -- :: Int   -> IO QSemN
20           waitQSemN,    -- :: QSemN -> Int -> IO ()
21           signalQSemN   -- :: QSemN -> Int -> IO ()
22       ) where
23
24 import Prelude
25
26 import Control.Concurrent.MVar
27
28 -- |A 'QSemN' is a quantity semaphore, in which the available
29 -- \"quantity\" may be signalled or waited for in arbitrary amounts.
30 newtype QSemN = QSemN (MVar (Int,[(Int,MVar ())]))
31
32 -- |Build a new 'QSemN' with a supplied initial quantity.
33 newQSemN :: Int -> IO QSemN 
34 newQSemN init = do
35    sem <- newMVar (init,[])
36    return (QSemN sem)
37
38 -- |Wait for the specified quantity to become available
39 waitQSemN :: QSemN -> Int -> IO ()
40 waitQSemN (QSemN sem) sz = do
41   (avail,blocked) <- takeMVar sem   -- gain ex. access
42   if (avail - sz) >= 0 then
43        -- discharging 'sz' still leaves the semaphore
44        -- in an 'unblocked' state.
45      putMVar sem (avail-sz,[])
46    else do
47      block <- newEmptyMVar
48      putMVar sem (avail, blocked++[(sz,block)])
49      takeMVar block
50
51 -- |Signal that a given quantity is now available from the 'QSemN'.
52 signalQSemN :: QSemN -> Int  -> IO ()
53 signalQSemN (QSemN sem) n = do
54    (avail,blocked)   <- takeMVar sem
55    (avail',blocked') <- free (avail+n) blocked
56    putMVar sem (avail',blocked')
57  where
58    free avail []    = return (avail,[])
59    free avail ((req,block):blocked)
60      | avail >= req = do
61         putMVar block ()
62         free (avail-req) blocked
63      | otherwise    = do
64         (avail',blocked') <- free avail blocked
65         return (avail',(req,block):blocked')