7e43908094d0888e82ab13cba20b8c308fdd6f13
[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 import Control.Exception ( mask_ )
28 import Data.Typeable
29
30 #include "Typeable.h"
31
32 -- |A 'QSemN' is a quantity semaphore, in which the available
33 -- \"quantity\" may be signalled or waited for in arbitrary amounts.
34 newtype QSemN = QSemN (MVar (Int,[(Int,MVar ())])) deriving Eq
35
36 INSTANCE_TYPEABLE0(QSemN,qSemNTc,"QSemN")
37
38 -- |Build a new 'QSemN' with a supplied initial quantity.
39 --  The initial quantity must be at least 0.
40 newQSemN :: Int -> IO QSemN
41 newQSemN initial =
42     if initial < 0
43     then fail "newQSemN: Initial quantity must be non-negative"
44     else do sem <- newMVar (initial, [])
45             return (QSemN sem)
46
47 -- |Wait for the specified quantity to become available
48 waitQSemN :: QSemN -> Int -> IO ()
49 waitQSemN (QSemN sem) sz = mask_ $ do
50   (avail,blocked) <- takeMVar sem   -- gain ex. access
51   let remaining = avail - sz
52   if remaining >= 0 then
53        -- discharging 'sz' still leaves the semaphore
54        -- in an 'unblocked' state.
55      putMVar sem (remaining,blocked)
56    else do
57      b <- newEmptyMVar
58      putMVar sem (avail, blocked++[(sz,b)])
59      takeMVar b
60
61 -- |Signal that a given quantity is now available from the 'QSemN'.
62 signalQSemN :: QSemN -> Int  -> IO ()
63 signalQSemN (QSemN sem) n = mask_ $ do
64    (avail,blocked)   <- takeMVar sem
65    (avail',blocked') <- free (avail+n) blocked
66    avail' `seq` putMVar sem (avail',blocked')
67  where
68    free avail []    = return (avail,[])
69    free avail ((req,b):blocked)
70      | avail >= req = do
71         putMVar b ()
72         free (avail-req) blocked
73      | otherwise    = do
74         (avail',blocked') <- free avail blocked
75         return (avail',(req,b):blocked')