1 -----------------------------------------------------------------------------
3 -- Module : Control.Concurrent.QSem
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
13 -----------------------------------------------------------------------------
15 module Control.Concurrent.QSem
17 newQSem, -- :: Int -> IO QSem
18 waitQSem, -- :: QSem -> IO ()
19 signalQSem -- :: QSem -> IO ()
23 import Control.Concurrent.MVar
25 -- General semaphores are also implemented readily in terms of shared
26 -- @MVar@s, only have to catch the case when the semaphore is tried
27 -- waited on when it is empty (==0). Implement this in the same way as
28 -- shared variables are implemented - maintaining a list of @MVar@s
29 -- representing threads currently waiting. The counter is a shared
30 -- variable, ensuring the mutual exclusion on its access.
32 newtype QSem = QSem (MVar (Int, [MVar ()]))
34 newQSem :: Int -> IO QSem
36 sem <- newMVar (init,[])
39 waitQSem :: QSem -> IO ()
40 waitQSem (QSem sem) = do
41 (avail,blocked) <- takeMVar sem -- gain ex. access
43 putMVar sem (avail-1,[])
47 Stuff the reader at the back of the queue,
48 so as to preserve waiting order. A signalling
49 process then only have to pick the MVar at the
50 front of the blocked list.
52 The version of waitQSem given in the paper could
55 putMVar sem (0, blocked++[block])
58 signalQSem :: QSem -> IO ()
59 signalQSem (QSem sem) = do
60 (avail,blocked) <- takeMVar sem
62 [] -> putMVar sem (avail+1,[])
64 (block:blocked') -> do
65 putMVar sem (0,blocked')