Document that the initial quantity for QSem and QSemN must be >= 0
[ghc-base.git] / Control / Concurrent / QSem.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Control.Concurrent.QSem
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 -- Simple quantity semaphores.
12 --
13 -----------------------------------------------------------------------------
14
15 module Control.Concurrent.QSem
16         ( -- * Simple Quantity Semaphores
17           QSem,         -- abstract
18           newQSem,      -- :: Int  -> IO QSem
19           waitQSem,     -- :: QSem -> IO ()
20           signalQSem    -- :: QSem -> IO ()
21         ) where
22
23 import Prelude
24 import Control.Concurrent.MVar
25 import Data.Typeable
26
27 #include "Typeable.h"
28
29 -- General semaphores are also implemented readily in terms of shared
30 -- @MVar@s, only have to catch the case when the semaphore is tried
31 -- waited on when it is empty (==0). Implement this in the same way as
32 -- shared variables are implemented - maintaining a list of @MVar@s
33 -- representing threads currently waiting. The counter is a shared
34 -- variable, ensuring the mutual exclusion on its access.
35
36 -- |A 'QSem' is a simple quantity semaphore, in which the available
37 -- \"quantity\" is always dealt with in units of one.
38 newtype QSem = QSem (MVar (Int, [MVar ()]))
39
40 INSTANCE_TYPEABLE0(QSem,qSemTc,"QSem")
41
42 -- |Build a new 'QSem' with a supplied initial quantity.
43 --  The initial quantity must be at least 0.
44 newQSem :: Int -> IO QSem
45 newQSem initial =
46     if initial < 0
47     then fail "newQSem: Initial quantity must be non-negative"
48     else do sem <- newMVar (initial, [])
49             return (QSem sem)
50
51 -- |Wait for a unit to become available
52 waitQSem :: QSem -> IO ()
53 waitQSem (QSem sem) = do
54    (avail,blocked) <- takeMVar sem  -- gain ex. access
55    if avail > 0 then
56      putMVar sem (avail-1,[])
57     else do
58      block <- newEmptyMVar
59       {-
60         Stuff the reader at the back of the queue,
61         so as to preserve waiting order. A signalling
62         process then only have to pick the MVar at the
63         front of the blocked list.
64
65         The version of waitQSem given in the paper could
66         lead to starvation.
67       -}
68      putMVar sem (0, blocked++[block])
69      takeMVar block
70
71 -- |Signal that a unit of the 'QSem' is available
72 signalQSem :: QSem -> IO ()
73 signalQSem (QSem sem) = do
74    (avail,blocked) <- takeMVar sem
75    case blocked of
76      [] -> putMVar sem (avail+1,[])
77
78      (block:blocked') -> do
79            putMVar sem (0,blocked')
80            putMVar block ()