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