1 -----------------------------------------------------------------------------
3 -- Module : Control.Concurrent.QSemN
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)
11 -- Quantity semaphores in which each thread may wait for an arbitrary
14 -----------------------------------------------------------------------------
16 module Control.Concurrent.QSemN
17 ( -- * General Quantity Semaphores
19 newQSemN, -- :: Int -> IO QSemN
20 waitQSemN, -- :: QSemN -> Int -> IO ()
21 signalQSemN -- :: QSemN -> Int -> IO ()
26 import Control.Concurrent.MVar
27 import Control.Exception ( mask_ )
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 ())]))
36 INSTANCE_TYPEABLE0(QSemN,qSemNTc,"QSemN")
38 -- |Build a new 'QSemN' with a supplied initial quantity.
39 -- The initial quantity must be at least 0.
40 newQSemN :: Int -> IO QSemN
43 then fail "newQSemN: Initial quantity must be non-negative"
44 else do sem <- newMVar (initial, [])
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)
58 putMVar sem (avail, blocked++[(sz,b)])
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')
68 free avail [] = return (avail,[])
69 free avail ((req,b):blocked)
72 free (avail-req) blocked
74 (avail',blocked') <- free avail blocked
75 return (avail',(req,b):blocked')