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
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 ())]))
35 INSTANCE_TYPEABLE0(QSemN,qSemNTc,"QSemN")
37 -- |Build a new 'QSemN' with a supplied initial quantity.
38 newQSemN :: Int -> IO QSemN
41 then fail "newQSemN: Initial quantity must be non-negative"
42 else do sem <- newMVar (initial, [])
45 -- |Wait for the specified quantity to become available
46 waitQSemN :: QSemN -> Int -> IO ()
47 waitQSemN (QSemN sem) sz = do
48 (avail,blocked) <- takeMVar sem -- gain ex. access
49 if (avail - sz) >= 0 then
50 -- discharging 'sz' still leaves the semaphore
51 -- in an 'unblocked' state.
52 putMVar sem (avail-sz,blocked)
55 putMVar sem (avail, blocked++[(sz,block)])
58 -- |Signal that a given quantity is now available from the 'QSemN'.
59 signalQSemN :: QSemN -> Int -> IO ()
60 signalQSemN (QSemN sem) n = do
61 (avail,blocked) <- takeMVar sem
62 (avail',blocked') <- free (avail+n) blocked
63 putMVar sem (avail',blocked')
65 free avail [] = return (avail,[])
66 free avail ((req,block):blocked)
69 free (avail-req) blocked
71 (avail',blocked') <- free avail blocked
72 return (avail',(req,block):blocked')