1{-# LANGUAGE DeriveFunctor #-}
2{-# LANGUAGE BangPatterns #-}
3{-# LANGUAGE MagicHash, UnboxedTuples, PatternGuards, ScopedTypeVariables, RankNTypes #-}
4-- | Concurrent queue for single reader, single writer
5module Control.Distributed.Process.Internal.CQueue
17import Prelude hiding (length, reverse)
18import Control.Concurrent.STM
33import Control.Applicative ((<$>), (<*>))
34import Control.Exception (mask_, onException)
35import System.Timeout (timeout)
36import Control.Distributed.Process.Internal.StrictMVar
37 ( StrictMVar(StrictMVar)
42import Control.Distributed.Process.Internal.StrictList
46import Data.Maybe (fromJust)
47import Data.Traversable (traverse)
48import GHC.MVar (MVar(MVar))
50import GHC.Prim (mkWeak#)
51import GHC.Weak (Weak(Weak))
53-- We use a TCHan rather than a Chan so that we have a non-blocking read
54data CQueue a = CQueue (StrictMVar (StrictList a)) -- Arrived
56 (TVar Int) -- Queue size
58newCQueue :: IO (CQueue a)
59newCQueue = CQueue <$> newMVar Nil <*> atomically newTChan <*> newTVarIO 0
61-- | Enqueue an element
64enqueue :: CQueue a -> a -> IO ()
65enqueue c !a = atomically (enqueueSTM c a)
67-- | Variant of enqueue for use in the STM monad.
68enqueueSTM :: CQueue a -> a -> STM ()
69enqueueSTM (CQueue _arrived incoming size) !a = do
79 = MatchMsg (m -> Maybe a)
83type MatchChunks m a = [Either [m -> Maybe a] [STM a]]
85chunkMatches :: [MatchOn m a] -> MatchChunks m a
87chunkMatches (MatchMsg m : ms) = Left (m : chk) : chunkMatches rest
88 where (chk, rest) = spanMatchMsg ms
89chunkMatches (MatchChan r : ms) = Right (r : chk) : chunkMatches rest
90 where (chk, rest) = spanMatchChan ms
92spanMatchMsg :: [MatchOn m a] -> ([m -> Maybe a], [MatchOn m a])
93spanMatchMsg [] = ([],[])
95 | MatchMsg msg <- m = (msg:msgs, rest)
96 | otherwise = ([], m:ms)
97 where !(msgs,rest) = spanMatchMsg ms
99spanMatchChan :: [MatchOn m a] -> ([STM a], [MatchOn m a])
100spanMatchChan [] = ([],[])
101spanMatchChan (m : ms)
102 | MatchChan stm <- m = (stm:stms, rest)
103 | otherwise = ([], m:ms)
104 where !(stms,rest) = spanMatchChan ms
106-- | Dequeue an element
108-- The timeout (if any) is applied only to waiting for incoming messages, not
109-- to checking messages that have already arrived
110dequeue :: forall m a.
112 -> BlockSpec -- ^ Blocking behaviour
113 -> [MatchOn m a] -- ^ List of matches
114 -> IO (Maybe a) -- ^ 'Nothing' only on timeout
115dequeue (CQueue arrived incoming size) blockSpec matchons = mask_ $ decrementJust $
117 Timeout n -> timeout n $ fmap fromJust run
120 [Right ports] -> -- channels only, this is easy:
122 NonBlocking -> atomically $ waitChans ports (return Nothing)
123 _ -> atomically $ waitChans ports retry
124 -- no onException needed
127 -- Decrement counter is smth is returned from the queue,
128 -- this is safe to use as method is called under a mask
129 -- and there is no 'unmasked' operation inside
131 traverse (either return (\x -> decrement >> return x)) =<< f
132 decrement = atomically $ modifyTVar' size pred
134 chunks = chunkMatches matchons
137 arr <- takeMVar arrived
139 r <- atomically $ tryReadTChan incoming
142 Just x -> grabNew (Snoc xs x)
146 waitChans ports on_block =
147 foldr orElse on_block (map (fmap (Just . Left)) ports)
150 -- First check the MatchChunks against the messages already in the
151 -- mailbox. For channel matches, we do a non-blocking check at
154 goCheck :: MatchChunks m a
155 -> StrictList m -- messages to check, in this order
156 -> IO (Maybe (Either a a))
158 goCheck [] old = goWait old
160 goCheck (Right ports : rest) old = do
161 r <- atomically $ waitChans ports (return Nothing) -- does not block
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 (Right r))
174 (old', Nothing) -> goCheck rest old'
175 -- use the result list, which is now left-biased
178 -- Construct an STM transaction that looks at the relevant channels
179 -- in the correct order.
181 mkSTM :: MatchChunks m a -> STM (Either m a)
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
196 -- The initial pass didn't find a message, so now we go into blocking
199 -- Contents of 'arrived' from now on is (old ++ new), and
200 -- messages that arrive are snocced onto new.
202 goWait :: StrictList m -> IO (Maybe (Either a a))
204 r <- waitIncoming `onException` putMVar arrived old
206 -- Nothing => non-blocking and no message
207 Nothing -> returnOld old Nothing
210 -- Left => message arrived in the process mailbox. We now have to
211 -- run through the MatchChunks checking each one, because we might
212 -- have a situation where the first chunk fails to match and the
213 -- second chunk is a channel match and there *is* a message in the
214 -- channel. In that case the channel wins.
216 Left m -> goCheck1 chunks m old
218 -- Right => message arrived on a channel first
220 Right a -> returnOld old (Just (Left a))
223 -- A message arrived in the process inbox; check the MatchChunks for
226 goCheck1 :: MatchChunks m a
227 -> m -- single message to check
228 -> StrictList m -- old messages we have already checked
229 -> IO (Maybe (Either a a))
231 goCheck1 [] m old = goWait (Snoc old m)
233 goCheck1 (Right ports : rest) m old = do
234 r <- atomically $ waitChans ports (return Nothing) -- does not block
236 Nothing -> goCheck1 rest m old
237 Just _ -> returnOld (Snoc old m) r
239 goCheck1 (Left matches : rest) m old = do
240 case checkMatches matches m of
241 Nothing -> goCheck1 rest m old
242 Just p -> returnOld old (Just (Right p))
244 -- a common pattern for putting back the arrived queue at the end
245 returnOld :: StrictList m -> Maybe (Either a a) -> IO (Maybe (Either a a))
246 returnOld old r = do putMVar arrived old; return r
248 -- as a side-effect, this left-biases the list
249 checkArrived :: [m -> Maybe a] -> StrictList m -> (StrictList m, Maybe a)
250 checkArrived matches list = go list Nil
252 go Nil Nil = (Nil, Nothing)
254 go (Append xs ys) tl = go xs (append ys tl)
255 go (Snoc xs x) tl = go xs (Cons x tl)
257 | Just y <- checkMatches matches x = (append xs tl, Just y)
258 | otherwise = let !(rest,r) = go xs tl in (Cons x rest, r)
260 checkMatches :: [m -> Maybe a] -> m -> Maybe a
261 checkMatches [] _ = Nothing
262 checkMatches (m:ms) a = case m a of Nothing -> checkMatches ms a
265-- | Weak reference to a CQueue
266mkWeakCQueue :: CQueue a -> IO () -> IO (Weak (CQueue a))
267mkWeakCQueue m@(CQueue (StrictMVar (MVar m#)) _ _) f = IO $ \s ->
268 case mkWeak# m# m f s of (# s1, w #) -> (# s1, Weak w #)
270queueSize :: CQueue a -> IO Int
271queueSize (CQueue _ _ size) = readTVarIO size
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list