1{-# LANGUAGE UndecidableInstances #-}
6-- Module : Streamly.Internal.Data.Stream.Async
7-- Copyright : (c) 2017 Composewell Technologies
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
14-- To run examples in this module:
16-- >>> import qualified Streamly.Prelude as Stream
17-- >>> import Control.Concurrent (threadDelay)
20-- threadDelay (n * 1000000) -- sleep for n seconds
21-- putStrLn (show n ++ " sec") -- print "n sec"
25module Streamly.Internal.Data.Stream.Async
42import Control.Concurrent (myThreadId)
43import Control.Monad.Base (MonadBase(..), liftBaseDefault)
44import Control.Monad.Catch (MonadThrow, throwM)
45import Control.Monad.Trans.Control (MonadBaseControl (..))
46import Control.Concurrent.MVar (newEmptyMVar)
47-- import Control.Monad.Error.Class (MonadError(..))
48import Control.Monad.IO.Class (MonadIO(..))
49import Control.Monad.Reader.Class (MonadReader(..))
50import Control.Monad.State.Class (MonadState(..))
51import Control.Monad.Trans.Class (MonadTrans(lift))
52import Data.Concurrent.Queue.MichaelScott (LinkedQueue, newQ, nullQ, tryPopR)
53import Data.IORef (IORef, newIORef, readIORef)
54import Data.Maybe (fromJust)
55#if __GLASGOW_HASKELL__ < 808
56import Data.Semigroup (Semigroup(..))
59import Prelude hiding (map)
60import qualified Data.Set as S
62import Streamly.Internal.Data.Atomics (atomicModifyIORefCAS)
63import Streamly.Internal.Data.Stream.SVar (fromSVar, fromSVarD)
64import Streamly.Internal.Data.SVar
65import Streamly.Internal.Data.Stream.StreamK.Type
66 (IsStream(..), Stream, mkStream, foldStream, adapt, foldStreamShared)
68import qualified Streamly.Internal.Data.Stream.StreamK as K (withLocal)
69import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
70import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
72#include "Instances.hs"
75-- >>> import Control.Concurrent (threadDelay)
78-- threadDelay (n * 1000000) -- sleep for n seconds
79-- putStrLn (show n ++ " sec") -- print "n sec"
83-------------------------------------------------------------------------------
85-------------------------------------------------------------------------------
87data WorkerStatus = Continue | Suspend
89{-# INLINE workLoopLIFO #-}
91 :: (MonadIO m, MonadBaseControl IO m)
92 => IORef [(RunInIO m, Stream m a)]
97workLoopLIFO q st sv winfo = run
101 stop = liftIO $ sendStop sv winfo
106 Just (RunInIO runin, m) -> do
107 -- XXX when we finish we need to send the monadic state back to
108 -- the parent so that the state can be merged back. We capture
109 -- and return the state in the stop continuation.
111 -- Instead of using the run function we can just restore the
112 -- monad state here. That way it can work easily for
113 -- distributed case as well.
114 r <- liftIO $ runin $
115 foldStreamShared st yieldk single (return Continue) m
122 res <- liftIO $ sendYield sv winfo (ChildYield a)
123 return $ if res then Continue else Suspend
126 res <- liftIO $ sendYield sv winfo (ChildYield a)
128 then foldStreamShared st yieldk single (return Continue) r
130 runInIO <- captureMonadState
131 liftIO $ enqueueLIFO sv q (runInIO, r)
134 dequeue = liftIO $ atomicModifyIORefCAS q $ \case
136 x : xs -> (xs, Just x)
138-- We duplicate workLoop for yield limit and no limit cases because it has
139-- around 40% performance overhead in the worst case.
141-- XXX we can pass yinfo directly as an argument here so that we do not have to
142-- make a check every time.
143{-# INLINE workLoopLIFOLimited #-}
145 :: forall m a. (MonadIO m, MonadBaseControl IO m)
146 => IORef [(RunInIO m, Stream m a)]
151workLoopLIFOLimited q st sv winfo = run
155 incrContinue = liftIO (incrementYieldLimit sv) >> return Continue
156 stop = liftIO $ sendStop sv winfo
161 Just (RunInIO runin, m) -> do
162 -- XXX This is just a best effort minimization of concurrency
163 -- to the yield limit. If the stream is made of concurrent
164 -- streams we do not reserve the yield limit in the constituent
165 -- streams before executing the action. This can be done
166 -- though, by sharing the yield limit ref with downstream
167 -- actions via state passing. Just a todo.
168 yieldLimitOk <- liftIO $ decrementYieldLimit sv
171 r <- liftIO $ runin $
172 foldStreamShared st yieldk single incrContinue m
177 -- Avoid any side effects, undo the yield limit decrement if we
178 -- never yielded anything.
180 enqueueLIFO sv q (RunInIO runin, m)
181 incrementYieldLimit sv
185 res <- liftIO $ sendYield sv winfo (ChildYield a)
186 return $ if res then Continue else Suspend
188 -- XXX can we pass on the yield limit downstream to limit the concurrency
189 -- of constituent streams.
191 res <- liftIO $ sendYield sv winfo (ChildYield a)
192 yieldLimitOk <- liftIO $ decrementYieldLimit sv
193 if res && yieldLimitOk
194 then foldStreamShared st yieldk single incrContinue r
196 runInIO <- captureMonadState
197 liftIO $ incrementYieldLimit sv
198 liftIO $ enqueueLIFO sv q (runInIO, r)
201 dequeue = liftIO $ atomicModifyIORefCAS q $ \case
203 x : xs -> (xs, Just x)
205-------------------------------------------------------------------------------
207-------------------------------------------------------------------------------
209-- XXX we can remove sv as it is derivable from st
211{-# INLINE workLoopFIFO #-}
213 :: (MonadIO m, MonadBaseControl IO m)
214 => LinkedQueue (RunInIO m, Stream m a)
219workLoopFIFO q st sv winfo = run
223 stop = liftIO $ sendStop sv winfo
225 work <- liftIO $ tryPopR q
228 Just (RunInIO runin, m) -> do
229 r <- liftIO $ runin $
230 foldStreamShared st yieldk single (return Continue) m
237 res <- liftIO $ sendYield sv winfo (ChildYield a)
238 return $ if res then Continue else Suspend
240 -- XXX in general we would like to yield "n" elements from a single stream
241 -- before moving on to the next. Single element granularity could be too
242 -- expensive in certain cases. Similarly, we can use time limit for
245 res <- liftIO $ sendYield sv winfo (ChildYield a)
246 runInIO <- captureMonadState
247 liftIO $ enqueueFIFO sv q (runInIO, r)
248 return $ if res then Continue else Suspend
250{-# INLINE workLoopFIFOLimited #-}
252 :: forall m a. (MonadIO m, MonadBaseControl IO m)
253 => LinkedQueue (RunInIO m, Stream m a)
258workLoopFIFOLimited q st sv winfo = run
262 stop = liftIO $ sendStop sv winfo
263 incrContinue = liftIO (incrementYieldLimit sv) >> return Continue
265 work <- liftIO $ tryPopR q
268 Just (RunInIO runin, m) -> do
269 yieldLimitOk <- liftIO $ decrementYieldLimit sv
272 r <- liftIO $ runin $
273 foldStreamShared st yieldk single incrContinue m
279 enqueueFIFO sv q (RunInIO runin, m)
280 incrementYieldLimit sv
284 res <- liftIO $ sendYield sv winfo (ChildYield a)
285 return $ if res then Continue else Suspend
288 res <- liftIO $ sendYield sv winfo (ChildYield a)
289 runInIO <- captureMonadState
290 liftIO $ enqueueFIFO sv q (runInIO, r)
291 yieldLimitOk <- liftIO $ decrementYieldLimit sv
292 if res && yieldLimitOk
295 incrementYieldLimit sv
298-------------------------------------------------------------------------------
300-- This code belongs in SVar.hs but is kept here for perf reasons
301-------------------------------------------------------------------------------
303-- XXX we have this function in this file because passing runStreamLIFO as a
304-- function argument to this function results in a perf degradation of more
305-- than 10%. Need to investigate what the root cause is.
306-- Interestingly, the same thing does not make any difference for Ahead.
307getLifoSVar :: forall m a. MonadAsync m
308 => State Stream m a -> RunInIO m -> IO (SVar Stream m a)
309getLifoSVar st mrun = do
310 outQ <- newIORef ([], 0)
311 outQMv <- newEmptyMVar
313 wfw <- newIORef False
314 running <- newIORef S.empty
315 q <- newIORef ([] :: [(RunInIO m, Stream m a)])
316 yl <- case getYieldLimit st of
317 Nothing -> return Nothing
318 Just x -> Just <$> newIORef x
319 rateInfo <- getYieldRateInfo st
321 stats <- newSVarStats
324 let isWorkFinished _ = null <$> readIORef q
326 let isWorkFinishedLimited sv = do
328 case remainingWork sv of
332 Nothing -> return False
333 qEmpty <- null <$> readIORef q
334 return $ qEmpty || yieldsDone
336 let getSVar :: SVar Stream m a
337 -> (SVar Stream m a -> m [ChildEvent a])
338 -> (SVar Stream m a -> m Bool)
339 -> (SVar Stream m a -> IO Bool)
340 -> (IORef [(RunInIO m, Stream m a)]
346 getSVar sv readOutput postProc workDone wloop = SVar
348 , outputQueueFromConsumer = undefined
350 , maxBufferLimit = getMaxBuffer st
351 , pushBufferSpace = undefined
352 , pushBufferPolicy = undefined
353 , pushBufferMVar = undefined
354 , maxWorkerLimit = min (getMaxThreads st) (getMaxBuffer st)
355 , yieldRateInfo = rateInfo
356 , outputDoorBell = outQMv
357 , outputDoorBellFromConsumer = undefined
358 , readOutputQ = readOutput sv
359 , postProcess = postProc sv
360 , workerThreads = running
361 , workLoop = wloop q st{streamVar = Just sv} sv
362 , enqueue = enqueueLIFO sv q
363 , isWorkDone = workDone sv
364 , isQueueDone = workDone sv
366 , svarStyle = AsyncVar
367 , svarStopStyle = StopNone
368 , svarStopBy = undefined
370 , workerCount = active
371 , accountThread = delThread sv
372 , workerStopMVar = undefined
374 , svarInspectMode = getInspectMode st
376 , aheadWorkQueue = undefined
377 , outputHeap = undefined
382 case getStreamRate st of
384 case getYieldLimit st of
385 Nothing -> getSVar sv readOutputQBounded
389 Just _ -> getSVar sv readOutputQBounded
391 isWorkFinishedLimited
394 case getYieldLimit st of
395 Nothing -> getSVar sv readOutputQPaced
399 Just _ -> getSVar sv readOutputQPaced
401 isWorkFinishedLimited
405getFifoSVar :: forall m a. MonadAsync m
406 => State Stream m a -> RunInIO m -> IO (SVar Stream m a)
407getFifoSVar st mrun = do
408 outQ <- newIORef ([], 0)
409 outQMv <- newEmptyMVar
411 wfw <- newIORef False
412 running <- newIORef S.empty
414 yl <- case getYieldLimit st of
415 Nothing -> return Nothing
416 Just x -> Just <$> newIORef x
417 rateInfo <- getYieldRateInfo st
419 stats <- newSVarStats
422 let isWorkFinished _ = nullQ q
423 let isWorkFinishedLimited sv = do
425 case remainingWork sv of
429 Nothing -> return False
431 return $ qEmpty || yieldsDone
433 let getSVar :: SVar Stream m a
434 -> (SVar Stream m a -> m [ChildEvent a])
435 -> (SVar Stream m a -> m Bool)
436 -> (SVar Stream m a -> IO Bool)
437 -> (LinkedQueue (RunInIO m, Stream m a)
443 getSVar sv readOutput postProc workDone wloop = SVar
445 , outputQueueFromConsumer = undefined
447 , maxBufferLimit = getMaxBuffer st
448 , pushBufferSpace = undefined
449 , pushBufferPolicy = undefined
450 , pushBufferMVar = undefined
451 , maxWorkerLimit = min (getMaxThreads st) (getMaxBuffer st)
452 , yieldRateInfo = rateInfo
453 , outputDoorBell = outQMv
454 , outputDoorBellFromConsumer = undefined
455 , readOutputQ = readOutput sv
456 , postProcess = postProc sv
457 , workerThreads = running
458 , workLoop = wloop q st{streamVar = Just sv} sv
459 , enqueue = enqueueFIFO sv q
460 , isWorkDone = workDone sv
461 , isQueueDone = workDone sv
463 , svarStyle = WAsyncVar
464 , svarStopStyle = StopNone
465 , svarStopBy = undefined
467 , workerCount = active
468 , accountThread = delThread sv
469 , workerStopMVar = undefined
471 , svarInspectMode = getInspectMode st
473 , aheadWorkQueue = undefined
474 , outputHeap = undefined
479 case getStreamRate st of
481 case getYieldLimit st of
482 Nothing -> getSVar sv readOutputQBounded
486 Just _ -> getSVar sv readOutputQBounded
488 isWorkFinishedLimited
491 case getYieldLimit st of
492 Nothing -> getSVar sv readOutputQPaced
496 Just _ -> getSVar sv readOutputQPaced
498 isWorkFinishedLimited
502{-# INLINABLE newAsyncVar #-}
503newAsyncVar :: MonadAsync m
504 => State Stream m a -> Stream m a -> m (SVar Stream m a)
506 mrun <- captureMonadState
507 sv <- liftIO $ getLifoSVar st mrun
510-- | Generate a stream asynchronously to keep it buffered, lazily consume
515{-# INLINABLE mkAsyncK #-}
516mkAsyncK :: (IsStream t, MonadAsync m) => t m a -> t m a
517mkAsyncK m = mkStream $ \st yld sng stp -> do
518 sv <- newAsyncVar (adaptState st) (toStream m)
519 foldStream st yld sng stp $ fromSVar sv
521{-# INLINE_NORMAL mkAsyncD #-}
522mkAsyncD :: MonadAsync m => D.Stream m a -> D.Stream m a
523mkAsyncD m = D.Stream step Nothing
526 step gst Nothing = do
527 sv <- newAsyncVar gst (D.fromStreamD m)
528 return $ D.Skip $ Just $ fromSVarD sv
530 step gst (Just (D.UnStream step1 st)) = do
533 D.Yield a s -> D.Yield a (Just $ D.Stream step1 s)
534 D.Skip s -> D.Skip (Just $ D.Stream step1 s)
538-- This is slightly faster than the CPS version above
540-- | Make the stream producer and consumer run concurrently by introducing a
541-- buffer between them. The producer thread evaluates the input stream until
542-- the buffer fills, it terminates if the buffer is full and a worker thread is
543-- kicked off again to evaluate the remaining stream when there is space in the
544-- buffer. The consumer consumes the stream lazily from the buffer.
548{-# INLINE_NORMAL mkAsync #-}
549mkAsync :: (K.IsStream t, MonadAsync m) => t m a -> t m a
550mkAsync = D.fromStreamD . mkAsyncD . D.toStreamD
552-- | Create a new SVar and enqueue one stream computation on it.
553{-# INLINABLE newWAsyncVar #-}
554newWAsyncVar :: MonadAsync m
555 => State Stream m a -> Stream m a -> m (SVar Stream m a)
556newWAsyncVar st m = do
557 mrun <- captureMonadState
558 sv <- liftIO $ getFifoSVar st mrun
561------------------------------------------------------------------------------
562-- Running streams concurrently
563------------------------------------------------------------------------------
565-- Concurrency rate control.
567-- Our objective is to create more threads on demand if the consumer is running
568-- faster than us. As soon as we encounter a concurrent composition we create a
569-- push pull pair of threads. We use an SVar for communication between the
570-- consumer, pulling from the SVar and the producer who is pushing to the SVar.
571-- The producer creates more threads if the SVar drains and becomes empty, that
572-- is the consumer is running faster.
574-- XXX Note 1: This mechanism can be problematic if the initial production
575-- latency is high, we may end up creating too many threads. So we need some
576-- way to monitor and use the latency as well. Having a limit on the dispatches
577-- (programmer controlled) may also help.
579-- TBD Note 2: We may want to run computations at the lower level of the
580-- composition tree serially even when they are composed using a parallel
581-- combinator. We can use 'serial' in place of 'async' and 'wSerial' in
582-- place of 'wAsync'. If we find that an SVar immediately above a computation
583-- gets drained empty we can switch to parallelizing the computation. For that
584-- we can use a state flag to fork the rest of the computation at any point of
585-- time inside the Monad bind operation if the consumer is running at a faster
588-- TBD Note 3: the binary operation ('parallel') composition allows us to
589-- dispatch a chunkSize of only 1. If we have to dispatch in arbitrary
590-- chunksizes we will need to compose the parallel actions using a data
591-- constructor (A Free container) instead so that we can divide it in chunks of
592-- arbitrary size before dispatching. If the stream is composed of
593-- hierarchically composed grains of different sizes then we can always switch
594-- to a desired granularity depending on the consumer speed.
596-- TBD Note 4: for pure work (when we are not in the IO monad) we can divide it
597-- into just the number of CPUs.
599-- | Join two computations on the currently running 'SVar' queue for concurrent
600-- execution. When we are using parallel composition, an SVar is passed around
601-- as a state variable. We try to schedule a new parallel computation on the
602-- SVar passed to us. The first time, when no SVar exists, a new SVar is
603-- created. Subsequently, 'joinStreamVarAsync' may get called when a computation
604-- already scheduled on the SVar is further evaluated. For example, when (a
605-- `parallel` b) is evaluated it calls a 'joinStreamVarAsync' to put 'a' and 'b' on
606-- the current scheduler queue.
608-- The 'SVarStyle' required by the current composition context is passed as one
609-- of the parameters. If the scheduling and composition style of the new
610-- computation being scheduled is different than the style of the current SVar,
611-- then we create a new SVar and schedule it on that. The newly created SVar
612-- joins as one of the computations on the current SVar queue.
614-- Cases when we need to switch to a new SVar:
616-- * (x `parallel` y) `parallel` (t `parallel` u) -- all of them get scheduled on the same SVar
617-- * (x `parallel` y) `parallel` (t `async` u) -- @t@ and @u@ get scheduled on a new child SVar
618-- because of the scheduling policy change.
619-- * if we 'adapt' a stream of type 'async' to a stream of type
620-- 'Parallel', we create a new SVar at the transitioning bind.
621-- * When the stream is switching from disjunctive composition to conjunctive
622-- composition and vice-versa we create a new SVar to isolate the scheduling
625forkSVarAsync :: (IsStream t, MonadAsync m)
626 => SVarStyle -> t m a -> t m a -> t m a
627forkSVarAsync style m1 m2 = mkStream $ \st yld sng stp -> do
629 AsyncVar -> newAsyncVar st (concurrently (toStream m1) (toStream m2))
630 WAsyncVar -> newWAsyncVar st (concurrently (toStream m1) (toStream m2))
631 _ -> error "illegal svar type"
632 foldStream st yld sng stp $ fromSVar sv
634 concurrently ma mb = mkStream $ \st yld sng stp -> do
635 runInIO <- captureMonadState
636 liftIO $ enqueue (fromJust $ streamVar st) $ (runInIO, mb)
637 foldStreamShared st yld sng stp ma
639{-# INLINE joinStreamVarAsync #-}
640joinStreamVarAsync :: (IsStream t, MonadAsync m)
641 => SVarStyle -> t m a -> t m a -> t m a
642joinStreamVarAsync style m1 m2 = mkStream $ \st yld sng stp ->
644 Just sv | svarStyle sv == style -> do
645 runInIO <- captureMonadState
646 liftIO $ enqueue sv $ (runInIO, toStream m2)
647 foldStreamShared st yld sng stp m1
648 _ -> foldStreamShared st yld sng stp (forkSVarAsync style m1 m2)
650------------------------------------------------------------------------------
651-- Semigroup and Monoid style compositions for parallel actions
652------------------------------------------------------------------------------
656-- | Merges two streams, both the streams may be evaluated concurrently,
657-- outputs from both are used as they arrive:
659-- >>> import Streamly.Prelude (async)
660-- >>> stream1 = Stream.yieldM (delay 4)
661-- >>> stream2 = Stream.yieldM (delay 2)
662-- >>> Stream.toList $ stream1 `async` stream2
667-- Multiple streams can be combined. With enough threads, all of them can be
668-- scheduled simultaneously:
670-- >>> stream3 = Stream.yieldM (delay 1)
671-- >>> Stream.toList $ stream1 `async` stream2 `async` stream3
675-- With 2 threads, only two can be scheduled at a time, when one of those
676-- finishes, the third one gets scheduled:
678-- >>> Stream.toList $ Stream.maxThreads 2 $ stream1 `async` stream2 `async` stream3
682-- With a single thread, it becomes serial:
684-- >>> Stream.toList $ Stream.maxThreads 1 $ stream1 `async` stream2 `async` stream3
688-- Only streams are scheduled for async evaluation, how actions within a
689-- stream are evaluated depends on the stream type. If it is a concurrent
690-- stream they will be evaluated concurrently.
692-- In the following example, both the streams are scheduled for concurrent
693-- evaluation but each individual stream is evaluated serially:
695-- >>> stream1 = Stream.fromListM $ Prelude.map delay [3,3] -- SerialT IO Int
696-- >>> stream2 = Stream.fromListM $ Prelude.map delay [1,1] -- SerialT IO Int
697-- >>> Stream.toList $ stream1 `async` stream2 -- IO [Int]
701-- If total threads are 2, the third stream is scheduled only after one of the
702-- first two has finished:
704-- >>> stream3 = Stream.fromListM $ Prelude.map delay [2,2] -- SerialT IO Int
705-- >>> Stream.toList $ Stream.maxThreads 2 $ stream1 `async` stream2 `async` stream3 -- IO [Int]
709-- Thus 'async' goes deep in first few streams rather than going wide in all
710-- streams. It prefers to evaluate the leftmost streams as much as possible.
711-- Because of this behavior, 'async' can be safely used to fold an infinite
712-- lazy container of streams.
714-- /Since: 0.2.0 ("Streamly")/
718async :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
719async = joinStreamVarAsync AsyncVar
724{-# DEPRECATED (<|) "Please use 'async' instead." #-}
726(<|) :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
729-- IMPORTANT: using a monomorphically typed and SPECIALIZED consMAsync makes a
730-- huge difference in the performance of consM in IsStream instance even we
731-- have a SPECIALIZE in the instance.
733-- | XXX we can implement it more efficienty by directly implementing instead
734-- of combining streams using async.
735{-# INLINE consMAsync #-}
736{-# SPECIALIZE consMAsync :: IO a -> AsyncT IO a -> AsyncT IO a #-}
737consMAsync :: MonadAsync m => m a -> AsyncT m a -> AsyncT m a
738consMAsync m r = fromStream $ K.yieldM m `async` (toStream r)
740------------------------------------------------------------------------------
742------------------------------------------------------------------------------
744-- | For 'AsyncT' streams:
747-- (<>) = 'Streamly.Prelude.async'
748-- (>>=) = flip . 'Streamly.Prelude.concatMapWith' 'Streamly.Prelude.async'
751-- A single 'Monad' bind behaves like a @for@ loop with iterations of the loop
752-- executed concurrently a la the 'async' combinator, producing results and
753-- side effects of iterations out of order:
756-- Stream.toList $ Stream.fromAsync $ do
757-- x <- Stream.fromList [2,1] -- foreach x in stream
758-- Stream.yieldM $ delay x
764-- Nested monad binds behave like nested @for@ loops with nested iterations
765-- executed concurrently, a la the 'async' combinator:
768-- Stream.toList $ Stream.fromAsync $ do
769-- x <- Stream.fromList [1,2] -- foreach x in stream
770-- y <- Stream.fromList [2,4] -- foreach y in stream
771-- Stream.yieldM $ delay (x + y)
779-- The behavior can be explained as follows. All the iterations corresponding
780-- to the element @1@ in the first stream constitute one output stream and all
781-- the iterations corresponding to @2@ constitute another output stream and
782-- these two output streams are merged using 'async'.
784-- /Since: 0.1.0 ("Streamly")/
787newtype AsyncT m a = AsyncT {getAsyncT :: Stream m a}
788 deriving (MonadTrans)
790-- | A demand driven left biased parallely composing IO stream of elements of
791-- type @a@. See 'AsyncT' documentation for more details.
793-- /Since: 0.2.0 ("Streamly")/
796type Async = AsyncT IO
798-- | Fix the type of a polymorphic stream as 'AsyncT'.
800-- /Since: 0.1.0 ("Streamly")/
803fromAsync :: IsStream t => AsyncT m a -> t m a
806instance IsStream AsyncT where
812------------------------------------------------------------------------------
814------------------------------------------------------------------------------
816-- Monomorphically typed version of "async" for better performance of Semigroup
818{-# INLINE mappendAsync #-}
819{-# SPECIALIZE mappendAsync :: AsyncT IO a -> AsyncT IO a -> AsyncT IO a #-}
820mappendAsync :: MonadAsync m => AsyncT m a -> AsyncT m a -> AsyncT m a
821mappendAsync m1 m2 = fromStream $ async (toStream m1) (toStream m2)
823instance MonadAsync m => Semigroup (AsyncT m a) where
826------------------------------------------------------------------------------
828------------------------------------------------------------------------------
830instance MonadAsync m => Monoid (AsyncT m a) where
834------------------------------------------------------------------------------
836------------------------------------------------------------------------------
838{-# INLINE apAsync #-}
839{-# SPECIALIZE apAsync :: AsyncT IO (a -> b) -> AsyncT IO a -> AsyncT IO b #-}
840apAsync :: MonadAsync m => AsyncT m (a -> b) -> AsyncT m a -> AsyncT m b
841apAsync (AsyncT m1) (AsyncT m2) =
842 let f x1 = K.concatMapBy async (pure . x1) m2
843 in AsyncT $ K.concatMapBy async f m1
845instance (Monad m, MonadAsync m) => Applicative (AsyncT m) where
847 pure = AsyncT . K.yield
851------------------------------------------------------------------------------
853------------------------------------------------------------------------------
855-- GHC: if we change the implementation of bindWith with arguments in a
856-- different order we see a significant performance degradation (~2x).
857{-# INLINE bindAsync #-}
858{-# SPECIALIZE bindAsync :: AsyncT IO a -> (a -> AsyncT IO b) -> AsyncT IO b #-}
859bindAsync :: MonadAsync m => AsyncT m a -> (a -> AsyncT m b) -> AsyncT m b
860bindAsync m f = fromStream $ K.bindWith async (adapt m) (\a -> adapt $ f a)
862-- GHC: if we specify arguments in the definition of (>>=) we see a significant
863-- performance degradation (~2x).
864instance MonadAsync m => Monad (AsyncT m) where
868------------------------------------------------------------------------------
870------------------------------------------------------------------------------
872MONAD_COMMON_INSTANCES(AsyncT, MONADPARALLEL)
874------------------------------------------------------------------------------
876------------------------------------------------------------------------------
878-- | XXX we can implement it more efficienty by directly implementing instead
879-- of combining streams using wAsync.
880{-# INLINE consMWAsync #-}
881{-# SPECIALIZE consMWAsync :: IO a -> WAsyncT IO a -> WAsyncT IO a #-}
882consMWAsync :: MonadAsync m => m a -> WAsyncT m a -> WAsyncT m a
883consMWAsync m r = fromStream $ K.yieldM m `wAsync` (toStream r)
887-- | For singleton streams, 'wAsync' is the same as 'async'. See 'async' for
888-- singleton stream behavior. For multi-element streams, while 'async' is left
889-- biased i.e. it tries to evaluate the left side stream as much as possible,
890-- 'wAsync' tries to schedule them both fairly. In other words, 'async' goes
891-- deep while 'wAsync' goes wide. However, outputs are always used as they
894-- With a single thread, 'async' starts behaving like 'serial' while 'wAsync'
895-- starts behaving like 'wSerial'.
897-- >>> import Streamly.Prelude (wAsync)
898-- >>> stream1 = Stream.fromList [1,2,3]
899-- >>> stream2 = Stream.fromList [4,5,6]
900-- >>> Stream.toList $ Stream.fromAsync $ Stream.maxThreads 1 $ stream1 `async` stream2
903-- >>> Stream.toList $ Stream.fromWAsync $ Stream.maxThreads 1 $ stream1 `wAsync` stream2
906-- With two threads available, and combining three streams:
908-- >>> stream3 = Stream.fromList [7,8,9]
909-- >>> Stream.toList $ Stream.fromAsync $ Stream.maxThreads 2 $ stream1 `async` stream2 `async` stream3
910-- [1,2,3,4,5,6,7,8,9]
912-- >>> Stream.toList $ Stream.fromWAsync $ Stream.maxThreads 2 $ stream1 `wAsync` stream2 `wAsync` stream3
913-- [1,4,2,7,5,3,8,6,9]
915-- This operation cannot be used to fold an infinite lazy container of streams,
916-- because it schedules all the streams in a round robin manner.
918-- Note that 'WSerialT' and single threaded 'WAsyncT' both interleave streams
919-- but the exact scheduling is slightly different in both cases.
923-- /Since: 0.2.0 ("Streamly")/
925-- Scheduling details:
927-- This is how the execution of the above example proceeds:
929-- 1. The scheduler queue is initialized with @[S.fromList [1,2,3],
930-- (S.fromList [4,5,6]) \<> (S.fromList [7,8,9])]@ assuming the head of the
931-- queue is represented by the rightmost item.
932-- 2. @S.fromList [1,2,3]@ is executed, yielding the element @1@ and putting
933-- @[2,3]@ at the back of the scheduler queue. The scheduler queue now looks
934-- like @[(S.fromList [4,5,6]) \<> (S.fromList [7,8,9]), S.fromList [2,3]]@.
935-- 3. Now @(S.fromList [4,5,6]) \<> (S.fromList [7,8,9])@ is picked up for
936-- execution, @S.fromList [7,8,9]@ is added at the back of the queue and
937-- @S.fromList [4,5,6]@ is executed, yielding the element @4@ and adding
938-- @S.fromList [5,6]@ at the back of the queue. The queue now looks like
939-- @[S.fromList [2,3], S.fromList [7,8,9], S.fromList [5,6]]@.
940-- 4. Note that the scheduler queue expands by one more stream component in
941-- every pass because one more @<>@ is broken down into two components. At this
942-- point there are no more @<>@ operations to be broken down further and the
943-- queue has reached its maximum size. Now these streams are scheduled in
944-- round-robin fashion yielding @[2,7,5,3,8,6,9]@.
946-- As we see above, in a right associated expression composed with @<>@, only
947-- one @<>@ operation is broken down into two components in one execution,
948-- therefore, if we have @n@ streams composed using @<>@ it will take @n@
949-- scheduler passes to expand the whole expression. By the time @n-th@
950-- component is added to the scheduler queue, the first component would have
951-- received @n@ scheduler passes.
954wAsync :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
955wAsync = joinStreamVarAsync WAsyncVar
957-- | For 'WAsyncT' streams:
960-- (<>) = 'Streamly.Prelude.wAsync'
961-- (>>=) = flip . 'Streamly.Prelude.concatMapWith' 'Streamly.Prelude.wAsync'
964-- A single 'Monad' bind behaves like a @for@ loop with iterations of the loop
965-- executed concurrently a la the 'wAsync' combinator, producing results and
966-- side effects of iterations out of order:
969-- Stream.toList $ Stream.fromWAsync $ do
970-- x <- Stream.fromList [2,1] -- foreach x in stream
971-- Stream.yieldM $ delay x
977-- Nested monad binds behave like nested @for@ loops with nested iterations
978-- executed concurrently, a la the 'wAsync' combinator:
981-- Stream.toList $ Stream.fromWAsync $ do
982-- x <- Stream.fromList [1,2] -- foreach x in stream
983-- y <- Stream.fromList [2,4] -- foreach y in stream
984-- Stream.yieldM $ delay (x + y)
992-- The behavior can be explained as follows. All the iterations corresponding
993-- to the element @1@ in the first stream constitute one 'WAsyncT' output
994-- stream and all the iterations corresponding to @2@ constitute another
995-- 'WAsyncT' output stream and these two output streams are merged using
998-- The @W@ in the name stands for @wide@ or breadth wise scheduling in
999-- contrast to the depth wise scheduling behavior of 'AsyncT'.
1002-- import qualified "Streamly.Prelude" as S
1003-- import Control.Concurrent
1005-- main = (S.toList . S.'fromWAsync' . S.maxThreads 1 $ (S.fromList [1,2]) \<> (S.fromList [3,4])) >>= print
1011-- For this example, we are using @maxThreads 1@ so that concurrent thread
1012-- scheduling does not affect the results and make them unpredictable. Let's
1013-- now take a more general example:
1016-- main = (S.toList . S.'fromWAsync' . S.maxThreads 1 $ (S.fromList [1,2,3]) \<> (S.fromList [4,5,6]) \<> (S.fromList [7,8,9])) >>= print
1019-- [1,4,2,7,5,3,8,6,9]
1022-- This is how the execution of the above stream proceeds:
1024-- 1. The scheduler queue is initialized with @[S.fromList [1,2,3],
1025-- (S.fromList [4,5,6]) \<> (S.fromList [7,8,9])]@ assuming the head of the
1026-- queue is represented by the rightmost item.
1027-- 2. @S.fromList [1,2,3]@ is executed, yielding the element @1@ and putting
1028-- @[2,3]@ at the back of the scheduler queue. The scheduler queue now looks
1029-- like @[(S.fromList [4,5,6]) \<> (S.fromList [7,8,9]), S.fromList [2,3]]@.
1030-- 3. Now @(S.fromList [4,5,6]) \<> (S.fromList [7,8,9])@ is picked up for
1031-- execution, @S.fromList [7,8,9]@ is added at the back of the queue and
1032-- @S.fromList [4,5,6]@ is executed, yielding the element @4@ and adding
1033-- @S.fromList [5,6]@ at the back of the queue. The queue now looks like
1034-- @[S.fromList [2,3], S.fromList [7,8,9], S.fromList [5,6]]@.
1035-- 4. Note that the scheduler queue expands by one more stream component in
1036-- every pass because one more @<>@ is broken down into two components. At this
1037-- point there are no more @<>@ operations to be broken down further and the
1038-- queue has reached its maximum size. Now these streams are scheduled in
1039-- round-robin fashion yielding @[2,7,5,3,8,6,9]@.
1041-- As we see above, in a right associated expression composed with @<>@, only
1042-- one @<>@ operation is broken down into two components in one execution,
1043-- therefore, if we have @n@ streams composed using @<>@ it will take @n@
1044-- scheduler passes to expand the whole expression. By the time @n-th@
1045-- component is added to the scheduler queue, the first component would have
1046-- received @n@ scheduler passes.
1048-- Since all streams get interleaved, this operation is not suitable for
1049-- folding an infinite lazy container of infinite size streams. However, if
1050-- the streams are small, the streams on the left may get finished before more
1051-- streams are added to the scheduler queue from the right side of the
1052-- expression, so it may be possible to fold an infinite lazy container of
1053-- streams. For example, if the streams are of size @n@ then at most @n@
1054-- streams would be in the scheduler queue at a time.
1056-- Note that 'WSerialT' and 'WAsyncT' differ in their scheduling behavior,
1057-- therefore the output of 'WAsyncT' even with a single thread of execution is
1058-- not the same as that of 'WSerialT' See notes in 'WSerialT' for details about
1059-- its scheduling behavior.
1061-- Any exceptions generated by a constituent stream are propagated to the
1062-- output stream. The output and exceptions from a single stream are guaranteed
1063-- to arrive in the same order in the resulting stream as they were generated
1064-- in the input stream. However, the relative ordering of elements from
1065-- different streams in the resulting stream can vary depending on scheduling
1066-- and generation delays.
1068-- Similarly, the 'Monad' instance of 'WAsyncT' runs /all/ iterations fairly
1069-- concurrently using a round robin scheduling.
1072-- main = S.'drain' . S.'fromWAsync' $ do
1073-- n <- return 3 \<\> return 2 \<\> return 1
1075-- threadDelay (n * 1000000)
1076-- myThreadId >>= \\tid -> putStrLn (show tid ++ ": Delay " ++ show n)
1079-- ThreadId 40: Delay 1
1080-- ThreadId 39: Delay 2
1081-- ThreadId 38: Delay 3
1084-- /Since: 0.2.0 ("Streamly")/
1087newtype WAsyncT m a = WAsyncT {getWAsyncT :: Stream m a}
1088 deriving (MonadTrans)
1090-- | A round robin parallely composing IO stream of elements of type @a@.
1091-- See 'WAsyncT' documentation for more details.
1093-- /Since: 0.2.0 ("Streamly")/
1096type WAsync = WAsyncT IO
1098-- | Fix the type of a polymorphic stream as 'WAsyncT'.
1100-- /Since: 0.2.0 ("Streamly")/
1103fromWAsync :: IsStream t => WAsyncT m a -> t m a
1106instance IsStream WAsyncT where
1107 toStream = getWAsyncT
1108 fromStream = WAsyncT
1112------------------------------------------------------------------------------
1114------------------------------------------------------------------------------
1116{-# INLINE mappendWAsync #-}
1117{-# SPECIALIZE mappendWAsync :: WAsyncT IO a -> WAsyncT IO a -> WAsyncT IO a #-}
1118mappendWAsync :: MonadAsync m => WAsyncT m a -> WAsyncT m a -> WAsyncT m a
1119mappendWAsync m1 m2 = fromStream $ wAsync (toStream m1) (toStream m2)
1121instance MonadAsync m => Semigroup (WAsyncT m a) where
1122 (<>) = mappendWAsync
1124------------------------------------------------------------------------------
1126------------------------------------------------------------------------------
1128instance MonadAsync m => Monoid (WAsyncT m a) where
1132------------------------------------------------------------------------------
1134------------------------------------------------------------------------------
1136{-# INLINE apWAsync #-}
1137{-# SPECIALIZE apWAsync :: WAsyncT IO (a -> b) -> WAsyncT IO a -> WAsyncT IO b #-}
1138apWAsync :: MonadAsync m => WAsyncT m (a -> b) -> WAsyncT m a -> WAsyncT m b
1139apWAsync (WAsyncT m1) (WAsyncT m2) =
1140 let f x1 = K.concatMapBy wAsync (pure . x1) m2
1141 in WAsyncT $ K.concatMapBy wAsync f m1
1143-- GHC: if we specify arguments in the definition of (<*>) we see a significant
1144-- performance degradation (~2x).
1145instance (Monad m, MonadAsync m) => Applicative (WAsyncT m) where
1146 pure = WAsyncT . K.yield
1149------------------------------------------------------------------------------
1151------------------------------------------------------------------------------
1153-- GHC: if we change the implementation of bindWith with arguments in a
1154-- different order we see a significant performance degradation (~2x).
1155{-# INLINE bindWAsync #-}
1156{-# SPECIALIZE bindWAsync :: WAsyncT IO a -> (a -> WAsyncT IO b) -> WAsyncT IO b #-}
1157bindWAsync :: MonadAsync m => WAsyncT m a -> (a -> WAsyncT m b) -> WAsyncT m b
1158bindWAsync m f = fromStream $ K.bindWith wAsync (adapt m) (\a -> adapt $ f a)
1160-- GHC: if we specify arguments in the definition of (>>=) we see a significant
1161-- performance degradation (~2x).
1162instance MonadAsync m => Monad (WAsyncT m) where
1166------------------------------------------------------------------------------
1168------------------------------------------------------------------------------
1170MONAD_COMMON_INSTANCES(WAsyncT, MONADPARALLEL)
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