on 5fd4c2f help sign in
524 lines 19 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE ConstraintKinds #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE GeneralizedNewtypeDeriving#-}
6{-# LANGUAGE InstanceSigs #-}
7{-# LANGUAGE MultiParamTypeClasses #-}
8{-# LANGUAGE UndecidableInstances #-} -- XXX
10-- |
11-- Module : Streamly.Streams.Parallel
12-- Copyright : (c) 2017 Harendra Kumar
13--
14-- License : BSD3
15-- Maintainer : harendra.kumar@gmail.com
16-- Stability : experimental
17-- Portability : GHC
18--
19--
20module Streamly.Streams.Parallel
21 (
22 ParallelT
23 , Parallel
24 , parallely
25 , parallel
26 , parallelEndByFirst
27 , parallelEndByAny
28 , tee
30 -- * Function application
31 , mkParallel
32 , (|$)
33 , (|&)
34 , (|$.)
35 , (|&.)
36 )
37where
39import Control.Concurrent (myThreadId)
40import Control.Exception (SomeException(..), throwIO)
41import Control.Monad (ap)
42import Control.Monad.Base (MonadBase(..), liftBaseDefault)
43import Control.Monad.Catch (MonadThrow, throwM)
44-- import Control.Monad.Error.Class (MonadError(..))
45import Control.Monad.IO.Class (MonadIO(..))
46import Control.Monad.Reader.Class (MonadReader(..))
47import Control.Monad.State.Class (MonadState(..))
48import Control.Monad.Trans.Class (MonadTrans(lift))
49import Data.Functor (void)
50import Data.IORef (readIORef, writeIORef)
51import Data.Maybe (fromJust)
52import Data.Semigroup (Semigroup(..))
53import Prelude hiding (map)
55import qualified Data.Set as Set
57import Streamly.Streams.SVar (fromSVar, fromStreamVar)
58import Streamly.Streams.Serial (map)
59import Streamly.SVar
60import Streamly.Streams.StreamK (IsStream(..), Stream, mkStream, foldStream,
61 foldStreamShared, adapt)
62import qualified Streamly.Streams.StreamK as K
64#include "Instances.hs"
66-------------------------------------------------------------------------------
67-- Parallel
68-------------------------------------------------------------------------------
70{-# NOINLINE runOne #-}
71runOne
72 :: MonadIO m
73 => State Stream m a -> Stream m a -> Maybe WorkerInfo -> m ()
74runOne st m0 winfo =
75 case getYieldLimit st of
76 Nothing -> go m0
77 Just _ -> runOneLimited st m0 winfo
79 where
81 go m = do
82 liftIO $ decrementBufferLimit sv
83 foldStreamShared st yieldk single stop m
85 sv = fromJust $ streamVar st
87 stop = liftIO $ do
88 incrementBufferLimit sv
89 sendStop sv winfo
90 sendit a = liftIO $ void $ send sv (ChildYield a)
91 single a = sendit a >> (liftIO $ sendStop sv winfo)
92 yieldk a r = sendit a >> go r
94runOneLimited
95 :: MonadIO m
96 => State Stream m a -> Stream m a -> Maybe WorkerInfo -> m ()
97runOneLimited st m0 winfo = go m0
99 where
101 go m = do
102 yieldLimitOk <- liftIO $ decrementYieldLimit sv
103 if yieldLimitOk
104 then do
105 liftIO $ decrementBufferLimit sv
106 foldStreamShared st yieldk single stop m
107 else liftIO $ cleanupSVarFromWorker sv
109 sv = fromJust $ streamVar st
111 stop = liftIO $ do
112 incrementBufferLimit sv
113 incrementYieldLimit sv
114 sendStop sv winfo
115 sendit a = liftIO $ void $ send sv (ChildYield a)
116 single a = sendit a >> (liftIO $ sendStop sv winfo)
117 yieldk a r = sendit a >> go r
119{-# NOINLINE forkSVarPar #-}
120forkSVarPar :: (IsStream t, MonadAsync m)
121 => SVarStopStyle -> t m a -> t m a -> t m a
122forkSVarPar ss m r = mkStream $ \st yld sng stp -> do
123 sv <- newParallelVar ss st
124 pushWorkerPar sv (runOne st{streamVar = Just sv} $ toStream m)
125 case ss of
126 StopBy -> liftIO $ do
127 set <- readIORef (workerThreads sv)
128 writeIORef (svarStopBy sv) $ Set.elemAt 0 set
129 _ -> return ()
130 pushWorkerPar sv (runOne st{streamVar = Just sv} $ toStream r)
131 foldStream st yld sng stp (fromSVar sv)
133{-# INLINE joinStreamVarPar #-}
134joinStreamVarPar :: (IsStream t, MonadAsync m)
135 => SVarStyle -> SVarStopStyle -> t m a -> t m a -> t m a
136joinStreamVarPar style ss m1 m2 = mkStream $ \st yld sng stp ->
137 case streamVar st of
138 Just sv | svarStyle sv == style && svarStopStyle sv == ss -> do
139 pushWorkerPar sv (runOne st $ toStream m1)
140 foldStreamShared st yld sng stp m2
141 _ -> foldStreamShared st yld sng stp (forkSVarPar ss m1 m2)
143-- | XXX we can implement it more efficienty by directly implementing instead
144-- of combining streams using parallel.
145{-# INLINE consMParallel #-}
146{-# SPECIALIZE consMParallel :: IO a -> ParallelT IO a -> ParallelT IO a #-}
147consMParallel :: MonadAsync m => m a -> ParallelT m a -> ParallelT m a
148consMParallel m r = fromStream $ K.yieldM m `parallel` (toStream r)
150-- | Polymorphic version of the 'Semigroup' operation '<>' of 'ParallelT'
151-- Merges two streams concurrently.
152--
153-- @since 0.2.0
154{-# INLINE parallel #-}
155parallel :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
156parallel = joinStreamVarPar ParallelVar StopNone
158-- This is a co-parallel like combinator for streams, where first stream is the
159-- main stream and the rest are just supporting it, when the first ends
160-- everything ends.
161--
162-- | Like `parallel` but stops the output as soon as the first stream stops.
163--
164-- @since 0.7.0
165{-# INLINE parallelEndByFirst #-}
166parallelEndByFirst :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
167parallelEndByFirst = joinStreamVarPar ParallelVar StopBy
169-- This is a race like combinator for streams.
170--
171-- | Like `parallel` but stops the output as soon as any of the two streams
172-- stops.
173--
174-- @since 0.7.0
175{-# INLINE parallelEndByAny #-}
176parallelEndByAny :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
177parallelEndByAny = joinStreamVarPar ParallelVar StopAny
179------------------------------------------------------------------------------
180-- Convert a stream to parallel
181------------------------------------------------------------------------------
183mkParallel :: (IsStream t, MonadAsync m) => t m a -> m (t m a)
184mkParallel m = do
185 sv <- newParallelVar StopNone defState
186 pushWorkerPar sv (runOne defState{streamVar = Just sv} $ toStream m)
187 return $ fromSVar sv
189------------------------------------------------------------------------------
190-- Stream to stream concurrent function application
191------------------------------------------------------------------------------
193{-# INLINE applyParallel #-}
194applyParallel :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> t m a -> t m b
195applyParallel f m = mkStream $ \st yld sng stp -> do
196 sv <- newParallelVar StopNone (adaptState st)
197 pushWorkerPar sv (runOne st{streamVar = Just sv} (toStream m))
198 foldStream st yld sng stp $ f $ fromSVar sv
200------------------------------------------------------------------------------
201-- Stream runner concurrent function application
202------------------------------------------------------------------------------
204{-# INLINE foldParallel #-}
205foldParallel :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> m b
206foldParallel f m = do
207 sv <- newParallelVar StopNone defState
208 pushWorkerPar sv (runOne defState{streamVar = Just sv} $ toStream m)
209 f $ fromSVar sv
211{-# INLINE teeToSVar #-}
212teeToSVar :: (IsStream t, MonadAsync m) => SVar Stream m a -> t m a -> t m a
213teeToSVar svr m = mkStream $ \st yld sng stp -> do
214 foldStreamShared st yld sng stp (go svr m)
216 where
218 go sv m0 = mkStream $ \st yld sng stp -> do
219 let stop = do
220 liftIO $ do
221 incrementBufferLimit sv
222 sendStop sv Nothing
223 -- XXX wait for Stop response event on exception channel,
224 -- drain the exception channel.
225 stp
226 sendit a = liftIO $ do
227 -- XXX check for exceptions before decrement so that we do not
228 -- block forever if the child already exited with an exception.
229 decrementBufferLimit sv
230 void $ send sv (ChildYield a)
231 single a = sendit a >> (liftIO $ sendStop sv Nothing) >> sng a
232 yieldk a r = sendit a >> yld a (go sv r)
233 in foldStreamShared st yieldk single stop m0
235-- In case of folds the roles of worker and parent on an SVar are reversed. The
236-- parent stream pushes values to an SVar instead of pulling from it and a
237-- worker thread running the fold pulls from the SVar and folds the stream. We
238-- keep a separate channel for pushing exceptions in the reverse direction i.e.
239-- from the fold to the parent stream.
240--
241-- NOTE: If we use fromSVar here it will kill the main computation (the parent)
242-- when the SVar goes away so we use fromStreamVar instead.
244{-# NOINLINE handleChildException #-}
245handleChildException :: SVar t m a -> SomeException -> IO ()
246handleChildException _sv e = do
247 -- tid <- myThreadId
248 -- void $ sendReverse sv (ChildStop tid (Just e))
249 throwIO e
251-- | Redirect a copy of the stream to a supplied fold and run it concurrently
252-- in an independent thread. The fold may buffer some elements. The buffer size
253-- is determined by the prevailing 'maxBuffer' setting.
254--
255-- @
256-- Stream m a -> m b
257-- |
258-- -----stream m a ---------------stream m a-----
259--
260-- @
261--
262-- @
263-- > S.drain $ S.tee (S.mapM_ print) (S.enumerateFromTo 1 2)
264-- 1
265-- 2
266-- @
267--
268-- Exceptions from the concurrently running fold are propagated to the current
269-- computation. Note that, because of buffering in the fold, exceptions may be
270-- delayed and may not correspond to the current element being processed in the
271-- parent stream, but we guarantee that the tap finishes and all exceptions
272-- from it are drained before the parent stream stops.
273--
274--
275-- Compare with 'tap'.
276--
277-- @since 0.7.0
278{-# INLINE tee #-}
279tee :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
280tee f m = mkStream $ \st yld sng stp -> do
281 -- Buffer size for the SVar is derived from the current state
282 sv <- newParallelVar StopNone (adaptState st)
283 -- XXX exception handling
284 -- XXX if we terminate due to an exception, do we need to actively
285 -- terminate the fold?
286 liftIO myThreadId >>= modifyThread sv
287 void $ doFork (void $ f $ fromStream $ fromStreamVar sv)
288 (svarMrun sv) (handleChildException sv)
289 foldStreamShared st yld sng stp (teeToSVar sv m)
291------------------------------------------------------------------------------
292-- Concurrent Application
293------------------------------------------------------------------------------
295infixr 0 |$
296infixr 0 |$.
298infixl 1 |&
299infixl 1 |&.
301-- | Parallel function application operator for streams; just like the regular
302-- function application operator '$' except that it is concurrent. The
303-- following code prints a value every second even though each stage adds a 1
304-- second delay.
305--
306--
307-- @
308-- drain $
309-- S.mapM (\\x -> threadDelay 1000000 >> print x)
310-- |$ S.repeatM (threadDelay 1000000 >> return 1)
311-- @
312--
313-- /Concurrent/
314--
315-- @since 0.3.0
316{-# INLINE (|$) #-}
317(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> t m a -> t m b
318f |$ x = applyParallel f x
320-- | Parallel reverse function application operator for streams; just like the
321-- regular reverse function application operator '&' except that it is
322-- concurrent.
323--
324-- @
325-- drain $
326-- S.repeatM (threadDelay 1000000 >> return 1)
327-- |& S.mapM (\\x -> threadDelay 1000000 >> print x)
328-- @
329--
330-- /Concurrent/
331--
332-- @since 0.3.0
333{-# INLINE (|&) #-}
334(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
335x |& f = f |$ x
337-- | Parallel function application operator; applies a @run@ or @fold@ function
338-- to a stream such that the fold consumer and the stream producer run in
339-- parallel. A @run@ or @fold@ function reduces the stream to a value in the
340-- underlying monad. The @.@ at the end of the operator is a mnemonic for
341-- termination of the stream.
342--
343-- @
344-- S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
345-- |$. S.repeatM (threadDelay 1000000 >> return 1)
346-- @
347--
348-- /Concurrent/
349--
350-- @since 0.3.0
351{-# INLINE (|$.) #-}
352(|$.) :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> m b
353f |$. x = foldParallel f x
355-- | Parallel reverse function application operator for applying a run or fold
356-- functions to a stream. Just like '|$.' except that the operands are reversed.
357--
358-- @
359-- S.repeatM (threadDelay 1000000 >> return 1)
360-- |&. S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
361-- @
362--
363-- /Concurrent/
364--
365-- @since 0.3.0
366{-# INLINE (|&.) #-}
367(|&.) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> m b) -> m b
368x |&. f = f |$. x
370------------------------------------------------------------------------------
371-- ParallelT
372------------------------------------------------------------------------------
374-- | Async composition with simultaneous traversal of all streams.
375--
376-- The Semigroup instance of 'ParallelT' concurrently /merges/ two streams,
377-- running both strictly concurrently and yielding elements from both streams
378-- as they arrive. When multiple streams are combined using 'ParallelT' each
379-- one is evaluated in its own thread and the results produced are presented in
380-- the combined stream on a first come first serve basis.
381--
382-- 'AsyncT' and 'WAsyncT' are /concurrent lookahead streams/ each with a
383-- specific type of consumption pattern (depth first or breadth first). Since
384-- they are lookahead, they may introduce certain default latency in starting
385-- more concurrent tasks for efficiency reasons or may put a default limitation
386-- on the resource consumption (e.g. number of concurrent threads for
387-- lookahead). If we look at the implementation detail, they both can share a
388-- pool of worker threads to evaluate the streams in the desired pattern and at
389-- the desired rate. However, 'ParallelT' uses a separate runtime thread to
390-- evaluate each stream.
391--
392-- 'WAsyncT' is similar to 'ParallelT', as both of them evaluate the
393-- constituent streams fairly in a round robin fashion.
394-- However, the key difference is that 'WAsyncT' is lazy or pull driven
395-- whereas 'ParallelT' is strict or push driven. 'ParallelT' immediately
396-- starts concurrent evaluation of both the streams (in separate threads) and
397-- later picks the results whereas 'WAsyncT' may wait for a certain latency
398-- threshold before initiating concurrent evaluation of the next stream. The
399-- concurrent scheduling of the next stream or the degree of concurrency is
400-- driven by the feedback from the consumer. In case of 'ParallelT' each stream
401-- is evaluated in a separate thread and results are /pushed/ to a shared
402-- output buffer, the evaluation rate is controlled by blocking when the buffer
403-- is full.
404--
405-- Concurrent lookahead streams are generally more efficient than
406-- 'ParallelT' and can work pretty efficiently even for smaller tasks because
407-- they do not necessarily use a separate thread for each task. So they should
408-- be preferred over 'ParallelT' especially when efficiency is a concern and
409-- simultaneous strict evaluation is not a requirement. 'ParallelT' is useful
410-- for cases when the streams are required to be evaluated simultaneously
411-- irrespective of how the consumer consumes them e.g. when we want to race
412-- two tasks and want to start both strictly at the same time or if we have
413-- timers in the parallel tasks and our results depend on the timers being
414-- started at the same time. We can say that 'ParallelT' is almost the same
415-- (modulo some implementation differences) as 'WAsyncT' when the latter is
416-- used with unlimited lookahead and zero latency in initiating lookahead.
417--
418-- @
419-- main = ('toList' . 'parallely' $ (fromFoldable [1,2]) \<> (fromFoldable [3,4])) >>= print
420-- @
421-- @
422-- [1,3,2,4]
423-- @
424--
425-- When streams with more than one element are merged, it yields whichever
426-- stream yields first without any bias, unlike the 'Async' style streams.
427--
428-- Any exceptions generated by a constituent stream are propagated to the
429-- output stream. The output and exceptions from a single stream are guaranteed
430-- to arrive in the same order in the resulting stream as they were generated
431-- in the input stream. However, the relative ordering of elements from
432-- different streams in the resulting stream can vary depending on scheduling
433-- and generation delays.
434--
435-- Similarly, the 'Monad' instance of 'ParallelT' runs /all/ iterations
436-- of the loop concurrently.
437--
438-- @
439-- import "Streamly"
440-- import qualified "Streamly.Prelude" as S
441-- import Control.Concurrent
442--
443-- main = 'drain' . 'parallely' $ do
444-- n <- return 3 \<\> return 2 \<\> return 1
445-- S.yieldM $ do
446-- threadDelay (n * 1000000)
447-- myThreadId >>= \\tid -> putStrLn (show tid ++ ": Delay " ++ show n)
448-- @
449-- @
450-- ThreadId 40: Delay 1
451-- ThreadId 39: Delay 2
452-- ThreadId 38: Delay 3
453-- @
454--
455-- Note that parallel composition can only combine a finite number of
456-- streams as it needs to retain state for each unfinished stream.
457--
458-- @since 0.1.0
459newtype ParallelT m a = ParallelT {getParallelT :: Stream m a}
460 deriving (MonadTrans)
462-- | A parallely composing IO stream of elements of type @a@.
463-- See 'ParallelT' documentation for more details.
464--
465-- @since 0.2.0
466type Parallel = ParallelT IO
468-- | Fix the type of a polymorphic stream as 'ParallelT'.
469--
470-- @since 0.1.0
471parallely :: IsStream t => ParallelT m a -> t m a
472parallely = adapt
474instance IsStream ParallelT where
475 toStream = getParallelT
476 fromStream = ParallelT
478 {-# INLINE consM #-}
479 {-# SPECIALIZE consM :: IO a -> ParallelT IO a -> ParallelT IO a #-}
480 consM = consMParallel
482 {-# INLINE (|:) #-}
483 {-# SPECIALIZE (|:) :: IO a -> ParallelT IO a -> ParallelT IO a #-}
484 (|:) = consM
486------------------------------------------------------------------------------
487-- Semigroup
488------------------------------------------------------------------------------
490{-# INLINE mappendParallel #-}
491{-# SPECIALIZE mappendParallel :: ParallelT IO a -> ParallelT IO a -> ParallelT IO a #-}
492mappendParallel :: MonadAsync m => ParallelT m a -> ParallelT m a -> ParallelT m a
493mappendParallel m1 m2 = fromStream $ parallel (toStream m1) (toStream m2)
495instance MonadAsync m => Semigroup (ParallelT m a) where
496 (<>) = mappendParallel
498------------------------------------------------------------------------------
499-- Monoid
500------------------------------------------------------------------------------
502instance MonadAsync m => Monoid (ParallelT m a) where
503 mempty = K.nil
504 mappend = (<>)
506------------------------------------------------------------------------------
507-- Monad
508------------------------------------------------------------------------------
510{-# INLINE bindParallel #-}
511{-# SPECIALIZE bindParallel :: ParallelT IO a -> (a -> ParallelT IO b) -> ParallelT IO b #-}
512bindParallel :: MonadAsync m => ParallelT m a -> (a -> ParallelT m b) -> ParallelT m b
513bindParallel m f = fromStream $ K.bindWith parallel (K.adapt m) (\a -> K.adapt $ f a)
515instance MonadAsync m => Monad (ParallelT m) where
516 return = pure
517 (>>=) = bindParallel
519------------------------------------------------------------------------------
520-- Other instances
521------------------------------------------------------------------------------
523MONAD_APPLICATIVE_INSTANCE(ParallelT,MONADPARALLEL)
524MONAD_COMMON_INSTANCES(ParallelT, MONADPARALLEL)