git.iko.soy/distributed-process
on 16fd0e2 help sign in
270 lines 9.0 kB history raw
1{-# LANGUAGE BangPatterns #-}
2{-# LANGUAGE MagicHash, UnboxedTuples, PatternGuards, ScopedTypeVariables, RankNTypes #-}
3-- | Concurrent queue for single reader, single writer
4module Control.Distributed.Process.Internal.CQueue
5 ( CQueue
6 , BlockSpec(..)
7 , MatchOn(..)
8 , newCQueue
9 , enqueue
10 , enqueueSTM
11 , dequeue
12 , mkWeakCQueue
13 , queueSize
14 ) where
16import Prelude hiding (length, reverse)
17import Control.Concurrent.STM
18 ( atomically
19 , STM
20 , TChan
21 , TVar
22 , modifyTVar'
23 , tryReadTChan
24 , newTChan
25 , newTVarIO
26 , writeTChan
27 , readTChan
28 , readTVarIO
29 , orElse
30 , retry
31 )
32import Control.Applicative ((<$>), (<*>))
33import Control.Exception (mask_, onException)
34import System.Timeout (timeout)
35import Control.Distributed.Process.Internal.StrictMVar
36 ( StrictMVar(StrictMVar)
37 , newMVar
38 , takeMVar
39 , putMVar
40 )
41import Control.Distributed.Process.Internal.StrictList
42 ( StrictList(..)
43 , append
44 )
45import Data.Maybe (fromJust)
46import GHC.MVar (MVar(MVar))
47import GHC.IO (IO(IO))
48import GHC.Prim (mkWeak#)
49import GHC.Weak (Weak(Weak))
51-- We use a TCHan rather than a Chan so that we have a non-blocking read
52data CQueue a = CQueue (StrictMVar (StrictList a)) -- Arrived
53 (TChan a) -- Incoming
54 (TVar Int) -- Queue size
56newCQueue :: IO (CQueue a)
57newCQueue = CQueue <$> newMVar Nil <*> atomically newTChan <*> newTVarIO 0
59-- | Enqueue an element
60--
61-- Enqueue is strict.
62enqueue :: CQueue a -> a -> IO ()
63enqueue c !a = atomically (enqueueSTM c a)
65-- | Variant of enqueue for use in the STM monad.
66enqueueSTM :: CQueue a -> a -> STM ()
67enqueueSTM (CQueue _arrived incoming size) !a = do
68 writeTChan incoming a
69 modifyTVar' size succ
71data BlockSpec =
72 NonBlocking
73 | Blocking
74 | Timeout Int
76data MatchOn m a
77 = MatchMsg (m -> Maybe a)
78 | MatchChan (STM a)
80type MatchChunks m a = [Either [m -> Maybe a] [STM a]]
82chunkMatches :: [MatchOn m a] -> MatchChunks m a
83chunkMatches [] = []
84chunkMatches (MatchMsg m : ms) = Left (m : chk) : chunkMatches rest
85 where (chk, rest) = spanMatchMsg ms
86chunkMatches (MatchChan r : ms) = Right (r : chk) : chunkMatches rest
87 where (chk, rest) = spanMatchChan ms
89spanMatchMsg :: [MatchOn m a] -> ([m -> Maybe a], [MatchOn m a])
90spanMatchMsg [] = ([],[])
91spanMatchMsg (m : ms)
92 | MatchMsg msg <- m = (msg:msgs, rest)
93 | otherwise = ([], m:ms)
94 where !(msgs,rest) = spanMatchMsg ms
96spanMatchChan :: [MatchOn m a] -> ([STM a], [MatchOn m a])
97spanMatchChan [] = ([],[])
98spanMatchChan (m : ms)
99 | MatchChan stm <- m = (stm:stms, rest)
100 | otherwise = ([], m:ms)
101 where !(stms,rest) = spanMatchChan ms
103-- | Dequeue an element
104--
105-- The timeout (if any) is applied only to waiting for incoming messages, not
106-- to checking messages that have already arrived
107dequeue :: forall m a.
108 CQueue m -- ^ Queue
109 -> BlockSpec -- ^ Blocking behaviour
110 -> [MatchOn m a] -- ^ List of matches
111 -> IO (Maybe a) -- ^ 'Nothing' only on timeout
112dequeue (CQueue arrived incoming size) blockSpec matchons = mask_ $ decrementJust $
113 case blockSpec of
114 Timeout n -> timeout n $ fmap fromJust run
115 _other ->
116 case chunks of
117 [Right ports] -> -- channels only, this is easy:
118 case blockSpec of
119 NonBlocking -> atomically $ waitChans ports (return Nothing)
120 _ -> atomically $ waitChans ports retry
121 -- no onException needed
122 _other -> run
123 where
124 -- Decrement counter is smth is returned from the queue,
125 -- this is safe to use as method is called under a mask
126 -- and there is no 'unmasked' operation inside
127 decrementJust f = do
128 mx <- f
129 case mx of
130 Just{} -> atomically $ modifyTVar' size pred
131 Nothing -> return ()
132 return mx
134 chunks = chunkMatches matchons
136 run = do
137 arr <- takeMVar arrived
138 let grabNew xs = do
139 r <- atomically $ tryReadTChan incoming
140 case r of
141 Nothing -> return xs
142 Just x -> grabNew (Snoc xs x)
143 arr' <- grabNew arr
144 goCheck chunks arr'
146 waitChans ports on_block =
147 foldr orElse on_block (map (fmap Just) ports)
149 --
150 -- First check the MatchChunks against the messages already in the
151 -- mailbox. For channel matches, we do a non-blocking check at
152 -- this point.
153 --
154 goCheck :: MatchChunks m a
155 -> StrictList m -- messages to check, in this order
156 -> IO (Maybe a)
158 goCheck [] old = goWait old
160 goCheck (Right ports : rest) old = do
161 r <- atomically $ waitChans ports (return Nothing) -- does not block
162 case r of
163 Just _ -> returnOld old r
164 Nothing -> goCheck rest old
166 goCheck (Left matches : rest) old = do
167 -- checkArrived might in principle take arbitrary time, so
168 -- we ought to call restore and use an exception handler. However,
169 -- the check is usually fast (just a comparison), and the overhead
170 -- of passing around restore and setting up exception handlers is
171 -- high. So just don't use expensive matchIfs!
172 case checkArrived matches old of
173 (old', Just r) -> returnOld old' (Just r)
174 (old', Nothing) -> goCheck rest old'
175 -- use the result list, which is now left-biased
177 --
178 -- Construct an STM transaction that looks at the relevant channels
179 -- in the correct order.
180 --
181 mkSTM :: MatchChunks m a -> STM (Either m a)
182 mkSTM [] = retry
183 mkSTM (Left _ : rest)
184 = fmap Left (readTChan incoming) `orElse` mkSTM rest
185 mkSTM (Right ports : rest)
186 = foldr orElse (mkSTM rest) (map (fmap Right) ports)
188 waitIncoming :: IO (Maybe (Either m a))
189 waitIncoming = case blockSpec of
190 NonBlocking -> atomically $ fmap Just stm `orElse` return Nothing
191 _ -> atomically $ fmap Just stm
192 where
193 stm = mkSTM chunks
195 --
196 -- The initial pass didn't find a message, so now we go into blocking
197 -- mode.
198 --
199 -- Contents of 'arrived' from now on is (old ++ new), and
200 -- messages that arrive are snocced onto new.
201 --
202 goWait old = do
203 r <- waitIncoming `onException` putMVar arrived old
204 case r of
205 -- Nothing => non-blocking and no message
206 Nothing -> returnOld old Nothing
207 Just e -> case e of
208 --
209 -- Left => message arrived in the process mailbox. We now have to
210 -- run through the MatchChunks checking each one, because we might
211 -- have a situation where the first chunk fails to match and the
212 -- second chunk is a channel match and there *is* a message in the
213 -- channel. In that case the channel wins.
214 --
215 Left m -> goCheck1 chunks m old
216 --
217 -- Right => message arrived on a channel first
218 --
219 Right a -> returnOld old (Just a)
221 --
222 -- A message arrived in the process inbox; check the MatchChunks for
223 -- a valid match.
224 --
225 goCheck1 :: MatchChunks m a
226 -> m -- single message to check
227 -> StrictList m -- old messages we have already checked
228 -> IO (Maybe a)
230 goCheck1 [] m old = goWait (Snoc old m)
232 goCheck1 (Right ports : rest) m old = do
233 r <- atomically $ waitChans ports (return Nothing) -- does not block
234 case r of
235 Nothing -> goCheck1 rest m old
236 Just _ -> returnOld (Snoc old m) r
238 goCheck1 (Left matches : rest) m old = do
239 case checkMatches matches m of
240 Nothing -> goCheck1 rest m old
241 Just p -> returnOld old (Just p)
243 -- a common pattern for putting back the arrived queue at the end
244 returnOld :: StrictList m -> Maybe a -> IO (Maybe a)
245 returnOld old r = do putMVar arrived old; return r
247 -- as a side-effect, this left-biases the list
248 checkArrived :: [m -> Maybe a] -> StrictList m -> (StrictList m, Maybe a)
249 checkArrived matches list = go list Nil
250 where
251 go Nil Nil = (Nil, Nothing)
252 go Nil r = go r Nil
253 go (Append xs ys) tl = go xs (append ys tl)
254 go (Snoc xs x) tl = go xs (Cons x tl)
255 go (Cons x xs) tl
256 | Just y <- checkMatches matches x = (append xs tl, Just y)
257 | otherwise = let !(rest,r) = go xs tl in (Cons x rest, r)
259 checkMatches :: [m -> Maybe a] -> m -> Maybe a
260 checkMatches [] _ = Nothing
261 checkMatches (m:ms) a = case m a of Nothing -> checkMatches ms a
262 Just b -> Just b
264-- | Weak reference to a CQueue
265mkWeakCQueue :: CQueue a -> IO () -> IO (Weak (CQueue a))
266mkWeakCQueue m@(CQueue (StrictMVar (MVar m#)) _ _) f = IO $ \s ->
267 case mkWeak# m# m f s of (# s1, w #) -> (# s1, Weak w #)
269queueSize :: CQueue a -> IO Int
270queueSize (CQueue _ _ size) = readTVarIO size