on 3d033ae help sign in
575 lines 22 kB history raw
1{-# LANGUAGE UndecidableInstances #-}
3#include "inline.hs"
5-- |
6-- Module : Streamly.Internal.Data.Stream.Parallel
7-- Copyright : (c) 2017 Harendra Kumar
8--
9-- License : BSD3
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
12-- Portability : GHC
13--
14--
15module Streamly.Internal.Data.Stream.Parallel
16 (
17 -- * Parallel Stream Type
18 ParallelT
19 , Parallel
20 , parallely
22 -- * Merge Concurrently
23 , parallel
24 , parallelFst
25 , parallelMin
27 -- * Evaluate Concurrently
28 , mkParallel
30 -- * Tap Concurrently
31 , tapAsync
32 , distributeAsync_
33 )
34where
36import Control.Concurrent (myThreadId, takeMVar)
37import Control.Monad (when)
38import Control.Monad.Base (MonadBase(..), liftBaseDefault)
39import Control.Monad.Catch (MonadThrow, throwM)
40-- import Control.Monad.Error.Class (MonadError(..))
41import Control.Monad.IO.Class (MonadIO(..))
42import Control.Monad.Reader.Class (MonadReader(..))
43import Control.Monad.State.Class (MonadState(..))
44import Control.Monad.Trans.Class (MonadTrans(lift))
45import Data.Functor (void)
46import Data.IORef (readIORef, writeIORef)
47import Data.Maybe (fromJust)
48#if __GLASGOW_HASKELL__ < 808
49import Data.Semigroup (Semigroup(..))
50#endif
51import Prelude hiding (map)
53import qualified Data.Set as Set
55import Streamly.Internal.Data.Stream.SVar
56 (fromSVar, fromProducer, fromConsumer, pushToFold)
57import Streamly.Internal.Data.Stream.StreamK
58 (IsStream(..), Stream, mkStream, foldStream, foldStreamShared, adapt)
60import Streamly.Internal.Data.SVar
62import qualified Streamly.Internal.Data.Stream.StreamK as K
63import qualified Streamly.Internal.Data.Stream.StreamD as D
65#include "Instances.hs"
67-------------------------------------------------------------------------------
68-- Parallel
69-------------------------------------------------------------------------------
71-------------------------------------------------------------------------------
72-- StreamK based worker routines
73-------------------------------------------------------------------------------
75{-# NOINLINE runOne #-}
76runOne
77 :: MonadIO m
78 => State Stream m a -> Stream m a -> Maybe WorkerInfo -> m ()
79runOne st m0 winfo =
80 case getYieldLimit st of
81 Nothing -> go m0
82 Just _ -> runOneLimited st m0 winfo
84 where
86 go m = do
87 liftIO $ decrementBufferLimit sv
88 foldStreamShared st yieldk single stop m
90 sv = fromJust $ streamVar st
92 stop = liftIO $ do
93 incrementBufferLimit sv
94 sendStop sv winfo
95 sendit a = liftIO $ void $ send sv (ChildYield a)
96 single a = sendit a >> (liftIO $ sendStop sv winfo)
97 yieldk a r = sendit a >> go r
99runOneLimited
100 :: MonadIO m
101 => State Stream m a -> Stream m a -> Maybe WorkerInfo -> m ()
102runOneLimited st m0 winfo = go m0
104 where
106 go m = do
107 yieldLimitOk <- liftIO $ decrementYieldLimit sv
108 if yieldLimitOk
109 then do
110 liftIO $ decrementBufferLimit sv
111 foldStreamShared st yieldk single stop m
112 else do
113 liftIO $ cleanupSVarFromWorker sv
114 liftIO $ sendStop sv winfo
116 sv = fromJust $ streamVar st
118 stop = liftIO $ do
119 incrementBufferLimit sv
120 incrementYieldLimit sv
121 sendStop sv winfo
122 sendit a = liftIO $ void $ send sv (ChildYield a)
123 single a = sendit a >> (liftIO $ sendStop sv winfo)
124 yieldk a r = sendit a >> go r
126-------------------------------------------------------------------------------
127-- Consing and appending a stream in parallel style
128-------------------------------------------------------------------------------
130-- Note that consing and appending requires StreamK as it would not scale well
131-- with StreamD unless we are only consing a very small number of streams or
132-- elements in a stream. StreamK allows us to manipulate control flow in a way
133-- which StreamD cannot allow. StreamK can make a jump without having to
134-- remember the past state.
136{-# NOINLINE forkSVarPar #-}
137forkSVarPar :: (IsStream t, MonadAsync m)
138 => SVarStopStyle -> t m a -> t m a -> t m a
139forkSVarPar ss m r = mkStream $ \st yld sng stp -> do
140 sv <- newParallelVar ss st
141 pushWorkerPar sv (runOne st{streamVar = Just sv} $ toStream m)
142 case ss of
143 StopBy -> liftIO $ do
144 set <- readIORef (workerThreads sv)
145 writeIORef (svarStopBy sv) $ Set.elemAt 0 set
146 _ -> return ()
147 pushWorkerPar sv (runOne st{streamVar = Just sv} $ toStream r)
148 foldStream st yld sng stp (fromSVar sv)
150{-# INLINE joinStreamVarPar #-}
151joinStreamVarPar :: (IsStream t, MonadAsync m)
152 => SVarStyle -> SVarStopStyle -> t m a -> t m a -> t m a
153joinStreamVarPar style ss m1 m2 = mkStream $ \st yld sng stp ->
154 case streamVar st of
155 Just sv | svarStyle sv == style && svarStopStyle sv == ss -> do
156 -- Here, WE ARE IN THE WORKER/PRODUCER THREAD, we know that because
157 -- the SVar exists. We are running under runOne and the output we
158 -- produce ultimately will be sent to the SVar by runOne.
159 --
160 -- If we came here the worker/runOne is evaluating a `parallel`
161 -- combinator. In this case, we always fork a new worker for the
162 -- first component (m1) in the parallel composition and continue to
163 -- evaluate the second component (m2) in the current worker thread.
164 --
165 -- When m1 is serially composed, the worker would evaluate it
166 -- without any further forks and the resulting output is sent to
167 -- the SVar and the evaluation terminates. If m1 is a `parallel`
168 -- composition of two streams the worker would again recurses here.
169 --
170 -- Similarly, when m2 is serially composed it gets evaluated here
171 -- and the resulting output is sent to the SVar by the runOne
172 -- wrapper. When m2 is composed with `parallel` it will again
173 -- recurse here and so on until it finally terminates.
174 --
175 -- When we create a right associated expression using `parallel`,
176 -- then m1 would always terminate without further forks or
177 -- recursion into this routine, therefore, the worker returns
178 -- immediately after evaluating it. And m2 would continue to
179 -- fork/recurse, therefore, the current thread always recurses and
180 -- forks new workers one after the other. This is a tail recursive
181 -- style execution, m2, the recursive expression always executed at
182 -- the tail.
183 --
184 -- When the expression is left associated, the worker spawned would
185 -- get the forking/recursing responsibility and then again the
186 -- worker spawned by that worker would fork, thus creating layer
187 -- over layer of workers and a chain of threads leading to a very
188 -- inefficient execution.
189 pushWorkerPar sv (runOne st $ toStream m1)
190 foldStreamShared st yld sng stp m2
191 _ ->
192 -- Here WE ARE IN THE CONSUMER THREAD, we create a new SVar, fork
193 -- worker threads to execute m1 and m2 and this thread starts
194 -- pulling the stream from the SVar.
195 foldStreamShared st yld sng stp (forkSVarPar ss m1 m2)
197-------------------------------------------------------------------------------
198-- User facing APIs
199-------------------------------------------------------------------------------
201-- | XXX we can implement it more efficienty by directly implementing instead
202-- of combining streams using parallel.
203{-# INLINE consMParallel #-}
204{-# SPECIALIZE consMParallel :: IO a -> ParallelT IO a -> ParallelT IO a #-}
205consMParallel :: MonadAsync m => m a -> ParallelT m a -> ParallelT m a
206consMParallel m r = fromStream $ K.yieldM m `parallel` (toStream r)
208-- | Execute two streams concurrently and merge their outputs. For example, if
209-- stream @a@ is a serial stream consisting of @a1, a2, a3@ and stream @b@ is a
210-- serial stream consisting of @b1, b2, b3@ then stream @a `parallel` b@ may
211-- produce @a1, b1, a2, b2, a3, b3@ or @a1, a2, b1, a3, b2, b3@ or some other
212-- combination depending on the rate at which the two streams produce elements.
213-- However, the relative order of outputs from a single stream e.g. @a1, a2,
214-- a3@ would remain the same in the resulting stream. The effects in the two
215-- streams may occur concurrently.
216--
217-- To run single actions (instead of streams) in parallel wrap them into
218-- singleton streams. The following trivial example is semantically equivalent
219-- to running the action @putStrLn "hello"@ in the current thread:
220--
221-- >>> S.toList $ S.yieldM (putStrLn "hello") `parallel` S.nil
222-- > hello
223-- > [()]
224--
225-- Run two actions concurrently:
226--
227-- >>> S.toList $ S.yieldM (putStrLn "hello") `parallel` S.yieldM (putStrLn "world")
228-- > hello
229-- > world
230-- > [(),()]
231--
232-- Run effects concurrently, disregarding their outputs:
233--
234-- >>> S.toList $ S.nilM (putStrLn "hello") `parallel` S.nilM (putStrLn "world")
235-- > hello
236-- > world
237-- > []
238--
239-- Run an effectful action, and a pure effect without any output, concurrently:
240--
241-- >>> S.toList $ S.yieldM (return 1) `parallel` S.nilM (putStrLn "world")
242-- world
243-- [1]
244--
245-- Note that 'parallel' is a polymorphic version of the @Semigroup@ operation
246-- @<>@ of 'ParallelT'.
247--
248-- `nilM` is currently @Internal@.
249--
250-- @since 0.2.0
251{-# INLINE parallel #-}
252parallel :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
253parallel = joinStreamVarPar ParallelVar StopNone
255-- This is a co-parallel like combinator for streams, where first stream is the
256-- main stream and the rest are just supporting it, when the first ends
257-- everything ends.
258--
259-- | Like `parallel` but stops the output as soon as the first stream stops.
260--
261-- /Internal/
262{-# INLINE parallelFst #-}
263parallelFst :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
264parallelFst = joinStreamVarPar ParallelVar StopBy
266-- This is a race like combinator for streams.
267--
268-- | Like `parallel` but stops the output as soon as any of the two streams
269-- stops.
270--
271-- /Internal/
272{-# INLINE parallelMin #-}
273parallelMin :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
274parallelMin = joinStreamVarPar ParallelVar StopAny
276------------------------------------------------------------------------------
277-- Convert a stream to parallel
278------------------------------------------------------------------------------
280-- | Generate a stream asynchronously to keep it buffered, lazily consume
281-- from the buffer.
282--
283-- /Internal/
284--
285mkParallel :: (IsStream t, MonadAsync m) => t m a -> t m a
286mkParallel m = mkStream $ \st yld sng stp -> do
287 sv <- newParallelVar StopNone (adaptState st)
288 -- pushWorkerPar sv (runOne st{streamVar = Just sv} $ toStream m)
289 D.toSVarParallel st sv $ D.toStreamD m
290 foldStream st yld sng stp $ fromSVar sv
292------------------------------------------------------------------------------
293-- Clone and distribute a stream in parallel
294------------------------------------------------------------------------------
296-- Tap a stream and send the elements to the specified SVar in addition to
297-- yielding them again.
298--
299-- XXX this could be written in StreamD style for better efficiency with fusion.
300--
301{-# INLINE teeToSVar #-}
302teeToSVar :: (IsStream t, MonadAsync m) => SVar Stream m a -> t m a -> t m a
303teeToSVar svr m = mkStream $ \st yld sng stp -> do
304 foldStreamShared st yld sng stp (go False m)
306 where
308 go False m0 = mkStream $ \st yld _ stp -> do
309 let drain = do
310 -- In general, a Stop event would come equipped with the result
311 -- of the fold. It is not used here but it would be useful in
312 -- applicative and distribute.
313 done <- fromConsumer svr
314 when (not done) $ do
315 liftIO $ withDiagMVar svr "teeToSVar: waiting to drain"
316 $ takeMVar (outputDoorBellFromConsumer svr)
317 drain
319 stopFold = do
320 liftIO $ sendStop svr Nothing
321 -- drain/wait until a stop event arrives from the fold.
322 drain
324 stop = stopFold >> stp
325 single a = do
326 done <- pushToFold svr a
327 yld a (go done (K.nilM stopFold))
328 yieldk a r = pushToFold svr a >>= \done -> yld a (go done r)
329 in foldStreamShared st yieldk single stop m0
331 go True m0 = m0
333-- In case of folds the roles of worker and parent on an SVar are reversed. The
334-- parent stream pushes values to an SVar instead of pulling from it and a
335-- worker thread running the fold pulls from the SVar and folds the stream. We
336-- keep a separate channel for pushing exceptions in the reverse direction i.e.
337-- from the fold to the parent stream.
338--
339-- Note: If we terminate due to an exception, we do not actively terminate the
340-- fold. It gets cleaned up by the GC.
342-- | Create an SVar with a fold consumer that will fold any elements sent to it
343-- using the supplied fold function.
344{-# INLINE newFoldSVar #-}
345newFoldSVar :: (IsStream t, MonadAsync m)
346 => State Stream m a -> (t m a -> m b) -> m (SVar Stream m a)
347newFoldSVar stt f = do
348 -- Buffer size for the SVar is derived from the current state
349 sv <- newParallelVar StopAny (adaptState stt)
351 -- Add the producer thread-id to the SVar.
352 liftIO myThreadId >>= modifyThread sv
354 void $ doFork (void $ f $ fromStream $ fromProducer sv)
355 (svarMrun sv)
356 (handleFoldException sv)
357 return sv
359-- NOTE: In regular pull style streams, the consumer stream is pulling elements
360-- from the SVar and we have several workers producing elements and pushing to
361-- SVar. In case of folds, we, the parent stream driving the fold, are the
362-- stream producing worker, we start an SVar and start pushing to the SVar, the
363-- fold on the other side of the SVar is the consumer stream.
364--
365-- In the pull stream case exceptions are propagated from the producing workers
366-- to the consumer stream, the exceptions are propagated on the same channel as
367-- the produced stream elements. However, in case of push style folds the
368-- current stream itself is the worker and the fold is the consumer, in this
369-- case we have to propagate the exceptions from the consumer to the producer.
370-- This is reverse of the pull case and we need a reverse direction channel
371-- to propagate the exception.
372--
373-- | Redirect a copy of the stream to a supplied fold and run it concurrently
374-- in an independent thread. The fold may buffer some elements. The buffer size
375-- is determined by the prevailing 'maxBuffer' setting.
376--
377-- @
378-- Stream m a -> m b
379-- |
380-- -----stream m a ---------------stream m a-----
381--
382-- @
383--
384-- @
385-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
386-- 1
387-- 2
388-- @
389--
390-- Exceptions from the concurrently running fold are propagated to the current
391-- computation. Note that, because of buffering in the fold, exceptions may be
392-- delayed and may not correspond to the current element being processed in the
393-- parent stream, but we guarantee that before the parent stream stops the tap
394-- finishes and all exceptions from it are drained.
395--
396--
397-- Compare with 'tap'.
398--
399-- /Internal/
400{-# INLINE tapAsync #-}
401tapAsync :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
402tapAsync f m = mkStream $ \st yld sng stp -> do
403 sv <- newFoldSVar st f
404 foldStreamShared st yld sng stp (teeToSVar sv m)
406-- | Concurrently distribute a stream to a collection of fold functions,
407-- discarding the outputs of the folds.
408--
409-- >>> S.drain $ distributeAsync_ [S.mapM_ print, S.mapM_ print] (S.enumerateFromTo 1 2)
410--
411-- @
412-- distributeAsync_ = flip (foldr tapAsync)
413-- @
414--
415-- /Internal/
416--
417{-# INLINE distributeAsync_ #-}
418distributeAsync_ :: (Foldable f, IsStream t, MonadAsync m)
419 => f (t m a -> m b) -> t m a -> t m a
420distributeAsync_ = flip (foldr tapAsync)
422------------------------------------------------------------------------------
423-- ParallelT
424------------------------------------------------------------------------------
426-- | Async composition with strict concurrent execution of all streams.
427--
428-- The 'Semigroup' instance of 'ParallelT' executes both the streams
429-- concurrently without any delay or without waiting for the consumer demand
430-- and /merges/ the results as they arrive. If the consumer does not consume
431-- the results, they are buffered upto a configured maximum, controlled by the
432-- 'maxBuffer' primitive. If the buffer becomes full the concurrent tasks will
433-- block until there is space in the buffer.
434--
435-- Both 'WAsyncT' and 'ParallelT', evaluate the constituent streams fairly in a
436-- round robin fashion. The key difference is that 'WAsyncT' might wait for the
437-- consumer demand before it executes the tasks whereas 'ParallelT' starts
438-- executing all the tasks immediately without waiting for the consumer demand.
439-- For 'WAsyncT' the 'maxThreads' limit applies whereas for 'ParallelT' it does
440-- not apply. In other words, 'WAsyncT' can be lazy whereas 'ParallelT' is
441-- strict.
442--
443-- 'ParallelT' is useful for cases when the streams are required to be
444-- evaluated simultaneously irrespective of how the consumer consumes them e.g.
445-- when we want to race two tasks and want to start both strictly at the same
446-- time or if we have timers in the parallel tasks and our results depend on
447-- the timers being started at the same time. If we do not have such
448-- requirements then 'AsyncT' or 'AheadT' are recommended as they can be more
449-- efficient than 'ParallelT'.
450--
451-- @
452-- main = ('toList' . 'parallely' $ (fromFoldable [1,2]) \<> (fromFoldable [3,4])) >>= print
453-- @
454-- @
455-- [1,3,2,4]
456-- @
457--
458-- When streams with more than one element are merged, it yields whichever
459-- stream yields first without any bias, unlike the 'Async' style streams.
460--
461-- Any exceptions generated by a constituent stream are propagated to the
462-- output stream. The output and exceptions from a single stream are guaranteed
463-- to arrive in the same order in the resulting stream as they were generated
464-- in the input stream. However, the relative ordering of elements from
465-- different streams in the resulting stream can vary depending on scheduling
466-- and generation delays.
467--
468-- Similarly, the 'Monad' instance of 'ParallelT' runs /all/ iterations
469-- of the loop concurrently.
470--
471-- @
472-- import "Streamly"
473-- import qualified "Streamly.Prelude" as S
474-- import Control.Concurrent
475--
476-- main = 'drain' . 'parallely' $ do
477-- n <- return 3 \<\> return 2 \<\> return 1
478-- S.yieldM $ do
479-- threadDelay (n * 1000000)
480-- myThreadId >>= \\tid -> putStrLn (show tid ++ ": Delay " ++ show n)
481-- @
482-- @
483-- ThreadId 40: Delay 1
484-- ThreadId 39: Delay 2
485-- ThreadId 38: Delay 3
486-- @
487--
488-- Note that parallel composition can only combine a finite number of
489-- streams as it needs to retain state for each unfinished stream.
490--
491-- /Since: 0.7.0 (maxBuffer applies to ParallelT streams)/
492--
493-- /Since: 0.1.0/
494newtype ParallelT m a = ParallelT {getParallelT :: Stream m a}
495 deriving (MonadTrans)
497-- | A parallely composing IO stream of elements of type @a@.
498-- See 'ParallelT' documentation for more details.
499--
500-- @since 0.2.0
501type Parallel = ParallelT IO
503-- | Fix the type of a polymorphic stream as 'ParallelT'.
504--
505-- @since 0.1.0
506parallely :: IsStream t => ParallelT m a -> t m a
507parallely = adapt
509instance IsStream ParallelT where
510 toStream = getParallelT
511 fromStream = ParallelT
513 {-# INLINE consM #-}
514 {-# SPECIALIZE consM :: IO a -> ParallelT IO a -> ParallelT IO a #-}
515 consM = consMParallel
517 {-# INLINE (|:) #-}
518 {-# SPECIALIZE (|:) :: IO a -> ParallelT IO a -> ParallelT IO a #-}
519 (|:) = consM
521------------------------------------------------------------------------------
522-- Semigroup
523------------------------------------------------------------------------------
525{-# INLINE mappendParallel #-}
526{-# SPECIALIZE mappendParallel :: ParallelT IO a -> ParallelT IO a -> ParallelT IO a #-}
527mappendParallel :: MonadAsync m => ParallelT m a -> ParallelT m a -> ParallelT m a
528mappendParallel m1 m2 = fromStream $ parallel (toStream m1) (toStream m2)
530instance MonadAsync m => Semigroup (ParallelT m a) where
531 (<>) = mappendParallel
533------------------------------------------------------------------------------
534-- Monoid
535------------------------------------------------------------------------------
537instance MonadAsync m => Monoid (ParallelT m a) where
538 mempty = K.nil
539 mappend = (<>)
541------------------------------------------------------------------------------
542-- Applicative
543------------------------------------------------------------------------------
545{-# INLINE apParallel #-}
546{-# SPECIALIZE apParallel :: ParallelT IO (a -> b) -> ParallelT IO a -> ParallelT IO b #-}
547apParallel :: MonadAsync m => ParallelT m (a -> b) -> ParallelT m a -> ParallelT m b
548apParallel (ParallelT m1) (ParallelT m2) =
549 let f x1 = K.concatMapBy parallel (pure . x1) m2
550 in ParallelT $ K.concatMapBy parallel f m1
552instance (Monad m, MonadAsync m) => Applicative (ParallelT m) where
553 {-# INLINE pure #-}
554 pure = ParallelT . K.yield
555 {-# INLINE (<*>) #-}
556 (<*>) = apParallel
558------------------------------------------------------------------------------
559-- Monad
560------------------------------------------------------------------------------
562{-# INLINE bindParallel #-}
563{-# SPECIALIZE bindParallel :: ParallelT IO a -> (a -> ParallelT IO b) -> ParallelT IO b #-}
564bindParallel :: MonadAsync m => ParallelT m a -> (a -> ParallelT m b) -> ParallelT m b
565bindParallel m f = fromStream $ K.bindWith parallel (K.adapt m) (\a -> K.adapt $ f a)
567instance MonadAsync m => Monad (ParallelT m) where
568 return = pure
569 (>>=) = bindParallel
571------------------------------------------------------------------------------
572-- Other instances
573------------------------------------------------------------------------------
575MONAD_COMMON_INSTANCES(ParallelT, MONADPARALLEL)