on a05abfc help sign in
streamly/docs/ConcurrentStreams.hs
780 lines 31 kB history raw
1{-# OPTIONS_GHC -fno-warn-unused-imports #-}
2-- |
3-- Module : ConcurrentStreams
4-- Copyright : (c) 2017 Composewell Technologies
5--
6-- License : BSD3
7-- Maintainer : streamly@composewell.com
8--
9-- In this tutorial we will show how streamly can be used for idiomatic and
10-- declarative concurrent programming. Before you go through this tutorial we
11-- recommend that you take a look at the Streamly serial streams tutorial.
13module ConcurrentStreams
14 (
15 -- * Concurrent Streams
16 -- $concurrentStreams
18 -- * Combining Streams
19 -- $flavors
21 -- * Imports and Supporting Code
22 -- $imports
24 -- * Generating Streams Concurrently
25 -- $generatingConcurrently
27 -- * Concurrent Pipeline Stages
28 -- $concurrentApplication
30 -- * Mapping Concurrently
31 -- $concurrentTransformation
33 -- * Merging Streams
35 -- ** Semigroup Style
37 -- *** Deep Speculative Composition ('Ahead')
38 -- $ahead
40 -- *** Deep Asynchronous Composition ('Async')
41 -- $async
43 -- *** Wide Asynchronous Composition ('WAsync')
44 -- $wasync
46 -- *** Parallel Asynchronous Composition ('Parallel')
47 -- $parallel
49 -- XXX we should deprecate and remove the mkAsync API
50 -- Custom composition
51 -- custom
53 -- ** Monoid Style
54 -- $monoid
56 -- * Nesting Streams
58 -- ** Monad
59 -- *** Deep Speculative Nesting ('Ahead')
60 -- $aheadNesting
62 -- *** Deep Asynchronous Nesting ('Async')
63 -- $concurrentNesting
65 -- *** Wide Asynchronous Nesting ('WAsync')
66 -- $wasyncNesting
68 -- *** Parallel Asynchronous Nesting ('Parallel')
69 -- $parallelNesting
71 -- ** Applicative
72 -- $applicative
74 -- * Zipping Streams
76 -- ** Parallel Zipping
77 -- $parallelzip
79 -- * Concurrent Programming
80 -- $concurrent
82 -- * Writing Concurrent Programs
83 -- $programs
85 -- * Where to go next?
86 -- $furtherReading
87 )
88where
90import Streamly.Prelude
91import Data.Semigroup
92import Control.Applicative
93import Control.Monad
94import Control.Monad.IO.Class (MonadIO(..))
95import Control.Monad.Trans.Class (MonadTrans (lift))
97-- CAUTION: please keep setup and imports sections in sync
99-- $setup
100-- >>> :m
101-- >>> import Data.Function ((&))
102-- >>> import Streamly.Prelude ((|:), (|&))
103-- >>> import qualified Streamly.Prelude as Stream
104-- >>> import qualified Streamly.Data.Fold as Fold
105--
106-- >>> import Control.Concurrent (threadDelay, myThreadId)
107-- >>> :{
108-- delay n = Stream.fromEffect $ do
109-- threadDelay (n * 1000000)
110-- tid <- myThreadId
111-- putStrLn (show tid ++ ": Delay " ++ show n)
112-- :}
113--
114-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
115-- >>> hSetBuffering stdout LineBuffering
116--
118-- $imports
119--
120-- In most of example snippets we do not repeat the imports. Where imports are
121-- not explicitly specified use the imports shown below.
122--
123-- >>> :m
124-- >>> import Data.Function ((&))
125-- >>> import Streamly.Prelude ((|:), (|&))
126-- >>> import qualified Streamly.Prelude as Stream
127-- >>> import qualified Streamly.Data.Fold as Fold
128--
129-- To illustrate concurrent vs serial composition aspects, we will use the
130-- following @delay@ function to introduce a sleep or delay specified in
131-- seconds. After the delay it prints the number of seconds it slept.
132--
133-- >>> import Control.Concurrent (threadDelay, myThreadId)
134-- >>> :{
135-- delay n = Stream.fromEffect $ do
136-- threadDelay (n * 1000000)
137-- tid <- myThreadId
138-- putStrLn (show tid ++ ": Delay " ++ show n)
139-- :}
140--
141-- For concurrent examples, use line buffering, otherwise output from different
142-- threads may get mixed:
143--
144-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
145-- >>> hSetBuffering stdout LineBuffering
146--
148-- $concurrentStreams
149--
150-- Many stream operations can be done concurrently:
151--
152-- * Streams can be generated concurrently.
153--
154-- * Streams can be merged concurrently.
155--
156-- * Multiple stages in a streaming pipeline can run concurrently.
157--
158-- * Streams can be mapped and zipped concurrently.
159--
160-- * In monadic composition they combine like a list transformer,
161-- providing concurrent non-determinism.
162--
163-- There are three basic concurrent stream styles, 'Ahead', 'Async', and
164-- 'Parallel'. The 'Ahead' style streams are similar to 'Serial' except that
165-- they can speculatively execute multiple stream actions concurrently in
166-- advance. 'Ahead' would return exactly the same stream as 'Serial' except
167-- that it may execute the actions concurrently. The 'Async' style streams,
168-- like 'Ahead', speculatively execute multiple stream actions in advance but
169-- return the results in their finishing order rather than in the stream
170-- traversal order. 'Parallel' is like 'Async' except that it provides
171-- unbounded parallelism instead of controlled parallelism.
172--
173-- For easy reference, we can classify the stream types based on /execution order/,
174-- /consumption order/, and /bounded or unbounded/ concurrency.
175-- Execution could be serial (i.e. synchronous) or asynchronous. In serial
176-- execution we execute the next action in the stream only after the previous
177-- one has finished executing. In asynchronous execution multiple actions in
178-- the stream can be executed asynchronously i.e. the next action can start
179-- executing even before the first one has finished. Consumption order
180-- determines the order in which the outputs generated by the composition are
181-- consumed. Consumption could be serial or asynchronous. In serial
182-- consumption, the outputs are consumed in the traversal order, in
183-- asynchronous consumption the outputs are consumed as they arrive i.e. first
184-- come first serve order.
185--
186-- +------------+--------------+--------------+--------------+
187-- | Type | Execution | Consumption | Concurrency |
188-- +============+==============+==============+==============+
189-- | 'Serial' | Serial | Serial | None |
190-- +------------+--------------+--------------+--------------+
191-- | 'Ahead' | Asynchronous | Serial | bounded |
192-- +------------+--------------+--------------+--------------+
193-- | 'Async' | Asynchronous | Asynchronous | bounded |
194-- +------------+--------------+--------------+--------------+
195-- | 'Parallel' | Asynchronous | Asynchronous | unbounded |
196-- +------------+--------------+--------------+--------------+
197--
198-- All these types can be freely inter-converted using type conversion
199-- combinators or type annotations, without any cost, to achieve the desired
200-- composition style. To force a particular type of composition, we coerce the
201-- stream type using the corresponding type adapting combinator from
202-- 'fromSerial', 'fromAhead', 'fromAsync', or 'fromParallel'. The default stream type
203-- is inferred as 'Serial' unless you change it by using one of the combinators
204-- or by using a type annotation.
206-- $flavors
207--
208-- Streams can be combined using '<>' or 'mappend' to form a
209-- composite. Composite streams can be interpreted in a depth first or
210-- breadth first manner using an appropriate type conversion before
211-- consumption. Deep (e.g. 'Serial') stream type variants traverse a
212-- composite stream in a depth first manner, such that each stream is
213-- traversed fully before traversing the next stream. Wide
214-- (e.g. 'WSerial') stream types traverse it in a breadth first
215-- manner, such that one element from each stream is traversed before
216-- coming back to the first stream again.
217--
218-- Each stream type has a wide traversal variant prefixed by 'W'. The wide
219-- variant differs only in the Semigroup\/Monoid, Applicative\/Monad
220-- compositions of the streams.
221-- The following table summarizes the basic types and the corresponding wide
222-- variants:
223--
224-- @
225-- +------------+-----------+
226-- | Deep | Wide |
227-- +============+===========+
228-- | 'Serial' | 'WSerial' |
229-- +------------+-----------+
230-- | 'Ahead' | 'WAhead' |
231-- +------------+-----------+
232-- | 'Async' | 'WAsync' |
233-- +------------+-----------+
234-- @
235--
236-- Other than these types there are also 'ZipSerial' and 'ZipAsync' types that
237-- zip streams serially or concurrently using 'Applicative' operation. These
238-- types are not monads they are only applicatives and they do not differ in
239-- 'Semigroup' composition.
240--
242-- $programs
243--
244-- When writing concurrent programs it is advised to not use the concurrent
245-- style stream combinators blindly at the top level. That might create too
246-- much concurrency where it is not even required, and can even degrade
247-- performance in some cases. In some cases it can also lead to surprising
248-- behavior because of some code that is supposed to be serial becoming
249-- concurrent. Please be aware that all concurrency capable APIs that you may
250-- have used under the scope of a concurrent stream combinator will become
251-- concurrent. For example if you have a 'repeatM' somewhere in your program
252-- and you use 'fromParallel' on top, the 'repeatM' becomes fully parallel,
253-- resulting into an infinite parallel execution . Instead, use the
254-- /Keep It Serial and Stupid/ principle, start with the default serial
255-- composition and enable concurrent combinators only when and where necessary.
256-- When you use a concurrent combinator you can use an explicit 'fromSerial'
257-- combinator to suppress any unnecessary concurrency under the scope of that
258-- combinator.
260-- $generatingConcurrently
261--
262-- Monadic construction and generation functions like 'consM', 'unfoldrM',
263-- 'replicateM', 'repeatM', 'iterateM' and 'fromFoldableM' work concurrently
264-- when used with appropriate stream type combinator. The pure versions of
265-- these APIs are not concurrent, however you can use the monadic versions even
266-- for pure computations by wrapping the pure value in a monad to get the
267-- concurrent generation capability where required.
268--
269-- The following code finishes in 3 seconds (6 seconds when serial):
270--
271-- >>> let p n = threadDelay (n * 1000000) >> return n
272-- >>> Stream.toList $ Stream.fromParallel $ p 3 |: p 2 |: p 1 |: Stream.nil
273-- [1,2,3]
274--
275-- >>> Stream.toList $ Stream.fromAhead $ p 3 |: p 2 |: p 1 |: Stream.nil
276-- [3,2,1]
277--
278-- The following finishes in 10 seconds (100 seconds when serial):
279--
280-- >>> Stream.drain $ Stream.fromAsync $ Stream.replicateM 10 $ p 10
281--
283-- $concurrentTransformation
284--
285-- Monadic transformation functions 'mapM' and 'sequence' work concurrently
286-- when used with appropriate stream type combinators. The pure versions do not
287-- work concurrently, however you can use the monadic versions even for pure
288-- computations to get the concurrent transformation capability where required.
289--
290-- This would print a value every second (2 seconds when serial):
291--
292-- >>> let p n = threadDelay (n * 1000000) >> return n
293-- >>> :{
294-- parMap =
295-- Stream.repeatM (p 1)
296-- & Stream.fromSerial -- repeatM is serial
297-- & Stream.mapM (\x -> p 1 >> print x)
298-- & Stream.fromAhead -- mapM is cocnurrent using Ahead style
299-- & Stream.drain
300-- :}
301--
303-- $concurrentApplication
304--
305-- The concurrent function application operators '|$' and '|&' apply a stream
306-- argument to a stream function concurrently to compose a concurrent pipeline
307-- of stream processing functions:
308--
309-- Because both the stages run concurrently, we would see a delay of only 1
310-- second instead of 2 seconds in the following:
311--
312-- >>> let p n = threadDelay (n * 1000000) >> return n
313-- >>> :{
314-- parApp =
315-- Stream.repeatM (p 1)
316-- |& Stream.mapM (\x -> p 1 >> print x)
317-- & Stream.drain
318-- :}
320-- $ahead
321--
322-- The 'Semigroup' operation '<>' of the 'Ahead' type combines two streams in a
323-- /serial depth first/ manner with concurrent lookahead. We use the 'fromAhead'
324-- type combinator to effect 'Ahead' style of composition. We can also use an
325-- explicit 'Ahead' type annotation for the stream to achieve the same effect.
326--
327-- When two streams are combined in this manner, the streams are traversed in
328-- depth first manner just like 'Serial', however it can execute the next
329-- stream concurrently and keep the results ready when its turn arrives.
330-- Concurrent execution of the next stream(s) is performed if the first stream
331-- blocks or if it cannot produce output at the rate that is enough to meet the
332-- consumer demand. Multiple streams can be executed concurrently to meet the
333-- demand. The following example would print the result in a second even
334-- though each action in each stream takes one second:
335--
336-- >>> p n = threadDelay 1000000 >> return n
337-- >>> stream1 = p 1 |: p 2 |: Stream.nil
338-- >>> stream2 = p 3 |: p 4 |: Stream.nil
339-- >>> Stream.toList $ Stream.fromAhead $ stream1 <> stream2
340-- [1,2,3,4]
341--
342-- Each stream is constructed 'fromAhead' and then both the streams are merged
343-- 'fromAhead', therefore, all the actions can run concurrently but the result is
344-- presented in serial order.
345--
346-- You can also use the polymorphic combinator 'ahead' in place of '<>' to
347-- compose any type of streams in this manner.
349-- $async
350--
351-- The 'Semigroup' operation '<>' of the 'Async' type combines the two
352-- streams in a depth first manner with parallel look ahead. We use the
353-- 'fromAsync' type combinator to effect 'Async' style of composition. We
354-- can also use the 'Async' type annotation for the stream type to achieve
355-- the same effect.
356--
357-- When two streams with multiple elements are combined in this manner, the
358-- streams are traversed in depth first manner just like 'Serial', however it
359-- can execute the next stream concurrently and return the results from it
360-- as they arrive i.e. the results from the next stream may be yielded even
361-- before the results from the first stream. Concurrent execution of the next
362-- stream(s) is performed if the first stream blocks or if it cannot produce
363-- output at the rate that is enough to meet the consumer demand. Multiple
364-- streams can be executed concurrently to meet the demand.
365-- In the example below each element in the stream introduces a constant delay
366-- of 1 second, however, it takes just one second to produce all the results.
367-- The results are not guaranteed to be in any particular order:
368--
369-- >>> p n = threadDelay 1000000 >> return n
370-- >>> stream1 = p 1 |: p 2 |: Stream.nil
371-- >>> stream2 = p 3 |: p 4 |: Stream.nil
372-- >>> Stream.toList $ Stream.fromAsync $ stream1 <> stream2
373-- ...
374--
375-- The constituent streams are also composed in 'Async' manner and the
376-- composition of streams too. We can compose the constituent streams to run
377-- serially, in that case it would take 2 seconds to produce all the results.
378-- The elements in the serial streams would be in serial order in the results:
379--
380-- >>> p n = threadDelay 1000000 >> return n
381-- >>> stream = (Stream.fromSerial stream1) <> (Stream.fromSerial stream2)
382-- >>> Stream.toList $ Stream.fromAsync stream
383-- ...
384--
385-- In the following example we can see that new threads are started when a
386-- computation blocks. Notice that the output from the stream with the
387-- shortest delay is printed first. The whole computation takes @maximum of
388-- (3, 2, 1) = 3@ seconds:
389--
390-- >>> Stream.drain $ Stream.fromAsync $ delay 3 <> delay 2 <> delay 1
391-- ThreadId ...: Delay 1
392-- ThreadId ...: Delay 2
393-- ThreadId ...: Delay 3
394--
395-- When we have a tree of computations composed using this style, the tree is
396-- traversed in DFS style just like the 'Serial' style, the only difference is
397-- that here we can move on to executing the next stream if a stream blocks.
398-- However, we will not start new threads if we have sufficient output to
399-- saturate the consumer. This is why we call it left-biased demand driven or
400-- adaptive concurrency style, the concurrency tends to stay on the left side
401-- of the composition as long as possible. More threads are started based on
402-- the pull rate of the consumer. The following example prints an output every
403-- second as all of the actions are concurrent.
404--
405-- >>> Stream.drain $ Stream.fromAsync $ (delay 1 <> delay 2) <> (delay 3 <> delay 4)
406-- ThreadId ...: Delay 1
407-- ThreadId ...: Delay 2
408-- ThreadId ...: Delay 3
409-- ThreadId ...: Delay 4
410--
411-- All the computations may even run in a single thread when more threads are
412-- not needed. As you can see, in the following example the computations are
413-- run in a single thread one after another, because none of them blocks.
414-- However, if the thread consuming the stream were faster than the producer
415-- then it would have started parallel threads for each computation to keep up
416-- even if none of them blocks:
417--
418-- >>> :{
419-- traced m = Stream.fromEffect (myThreadId >>= print) >> return m
420-- stream = traced (sqrt 9) <> traced (sqrt 16) <> traced (sqrt 25)
421-- main = Stream.drain $ Stream.fromAsync stream
422-- :}
423--
424-- Note that the order of printing in the above examples may change due to
425-- variations in scheduling latencies for concurrent threads.
426--
427-- The polymorphic version of the 'Async' binary operation '<>' is called
428-- 'async'. We can use 'async' to join streams in a left biased
429-- adaptively concurrent manner irrespective of the type, notice that we have
430-- not used the 'fromAsync' combinator in the following example:
431--
432-- >>> Stream.drain $ delay 3 `Stream.async` delay 2 `Stream.async` delay 1
433-- ThreadId ...: Delay 1
434-- ThreadId ...: Delay 2
435-- ThreadId ...: Delay 3
436--
437-- Since the concurrency provided by this operator is demand driven it cannot
438-- be used when the composed computations start timers that are relative to
439-- each other because all computations may not be started at the same time and
440-- therefore timers in all of them may not start at the same time. When
441-- relative timing among all computations is important or when we need to start
442-- all computations at once for any reason 'Parallel' style must be used
443-- instead.
444--
445-- 'Async' style utilizes resources optimally and should be preferred over
446-- 'Parallel' or 'WAsync' unless you really need those. 'Async' should be used
447-- when we know that the computations can run in parallel but we do not care if
448-- they actually run in parallel or not, that decision can be left to the
449-- scheduler based on demand. Also, note that 'async' operator can be used to fold
450-- infinite number of streams in contrast to the 'Parallel' or 'WAsync' styles,
451-- because it does not require us to run all of them at the same time in a fair
452-- manner.
454-- $wasync
455--
456-- The 'Semigroup' operation '<>' of the 'WAsync' type combines two streams in
457-- a concurrent manner using /breadth first traversal/. We use the 'fromWAsync'
458-- type combinator to effect 'WAsync' style of composition. We can also use the
459-- 'WAsync' type annotation for the stream to achieve the same effect.
460--
461-- When streams with multiple elements are combined in this manner, we traverse
462-- all the streams concurrently in a breadth first manner i.e. one action from
463-- each stream is performed and yielded to the resulting stream before we come
464-- back to the first stream again and so on. Even though we execute the actions
465-- in a breadth first order the outputs are consumed on a first come first
466-- serve basis.
467--
468-- In the following example we can see that outputs are produced in the breadth
469-- first traversal order but this is not guaranteed.
470--
471-- >>> stream1 = print 1 |: print 2 |: Stream.nil
472-- >>> stream2 = print 3 |: print 4 |: Stream.nil
473-- >>> Stream.drain $ Stream.fromWAsync $ stream1 <> stream2
474-- 1
475-- 3
476-- 2
477-- 4
478--
479-- The polymorphic version of the binary operation '<>' of the 'WAsync' type is
480-- 'wAsync'. We can use 'wAsync' to join streams using a breadth first
481-- concurrent traversal irrespective of the type, notice that we have not used
482-- the 'fromWAsync' combinator in the following example:
483--
484-- >>> Stream.drain $ delay 3 `Stream.wAsync` delay 2 `Stream.wAsync` delay 1
485-- ThreadId ...: Delay 1
486-- ThreadId ...: Delay 2
487-- ThreadId ...: Delay 3
488--
489-- Since the concurrency provided by this style is demand driven it may not
490-- be used when the composed computations start timers that are relative to
491-- each other because all computations may not be started at the same time and
492-- therefore timers in all of them may not start at the same time. When
493-- relative timing among all computations is important or when we need to start
494-- all computations at once for any reason 'Parallel' style must be used
495-- instead.
496--
498-- $parallel
499--
500-- The 'Semigroup' operation '<>' of the 'Parallel' type combines the two
501-- streams in a fairly concurrent manner with round robin scheduling. We use
502-- the 'fromParallel' type combinator to effect 'Parallel' style of composition.
503-- We can also use the 'Parallel' type annotation for the stream type to
504-- achieve the same effect.
505--
506-- When two streams with multiple elements are combined in this manner, the
507-- monadic actions in both the streams are performed concurrently with a fair
508-- round robin scheduling. The outputs are yielded in the order in which the
509-- actions complete. This is pretty similar to the 'WAsync' type, the
510-- difference is that 'WAsync' is adaptive to the consumer demand and may or
511-- may not execute all actions in parallel depending on the demand, whereas
512-- 'Parallel' runs all the streams in parallel irrespective of the demand.
513--
514-- The polymorphic version of the binary operation '<>' of the 'Parallel' type
515-- is 'parallel'. We can use 'parallel' to join streams in a fairly concurrent
516-- manner irrespective of the type, notice that we have not used the
517-- 'fromParallel' combinator in the following example:
518--
519-- >>> Stream.drain $ delay 3 `Stream.parallel` delay 2 `Stream.wAsync` delay 1
520-- ThreadId ...: Delay 1
521-- ThreadId ...: Delay 2
522-- ThreadId ...: Delay 3
523--
524-- Note that this style of composition cannot be used to combine infinite
525-- number of streams, as it will lead to an infinite sized scheduling queue.
526--
528-- XXX to be removed
529-- $custom
530--
531-- The 'mkAsync' API can be used to create references to asynchronously running
532-- stream computations. We can then use 'uncons' to explore the streams
533-- arbitrarily and then recompose individual elements to create a new stream.
534-- This way we can dynamically decide which stream to explore at any given
535-- time. Take an example of a merge sort of two sorted streams. We need to
536-- keep consuming items from the stream which has the lowest item in the sort
537-- order. This can be achieved using async references to streams. See
538-- "MergeSort.hs" in <https://github.com/composewell/streamly-examples Streamly Examples>.
540-- $monoid
541--
542-- All of the following are equivalent and start ten concurrent tasks each with
543-- a delay from 1 to 10 seconds, resulting in the printing of each number every
544-- second:
545--
546-- >>> :{
547-- main = do
548-- Stream.drain $ Stream.fromAsync $ foldMap delay [1..10]
549-- Stream.drain $ Stream.concatFoldableWith Stream.async (map delay [1..10])
550-- Stream.drain $ Stream.concatMapFoldableWith Stream.async delay [1..10]
551-- Stream.drain $ Stream.concatForFoldableWith Stream.async [1..10] delay
552-- :}
553--
555-- $aheadNesting
556--
557-- The 'Monad' composition of 'Ahead' type behaves just like 'Serial' except
558-- that it can speculatively perform a bounded number of next iterations of a
559-- loop concurrently.
560--
561-- >>> :{
562-- Stream.toList $ Stream.fromAhead $ do
563-- x <- Stream.fromFoldable [3,2,1]
564-- delay x
565-- return x
566-- :}
567-- ThreadId ...: Delay 1
568-- ThreadId ...: Delay 2
569-- ThreadId ...: Delay 3
570-- [3,2,1]
571--
572-- This code finishes in 3 seconds, 'Serial' would take 6 seconds. As we can
573-- see all the three iterations are concurrent and run in different threads,
574-- however, the results are returned in the serial order.
575--
576-- Concurrency is demand driven, when multiple streams are composed using this
577-- style, the iterations are executed in a depth first manner just like
578-- 'Serial' i.e. nested iterations are executed before we proceed to the next
579-- outer iteration. The only difference is that we may execute multiple future
580-- iterations concurrently and keep the results ready.
581--
582-- The 'fromAhead' type combinator can be used to switch to this style of
583-- composition. Alternatively, a type annotation can be used to specify the
584-- type of the stream as 'Ahead'.
585--
587-- $concurrentNesting
588--
589-- The 'Monad' composition of 'Async' type can perform the iterations of a
590-- loop concurrently.
591--
592-- >>> :{
593-- Stream.drain $ Stream.fromAsync $ do
594-- x <- Stream.fromFoldable [3,2,1]
595-- delay x
596-- :}
597-- ThreadId ...: Delay 1
598-- ThreadId ...: Delay 2
599-- ThreadId ...: Delay 3
600--
601-- As we can see the code after the @fromFoldable@ statement is run three
602-- times, once for each value of @x@. All the three iterations are concurrent
603-- and run in different threads. The iteration with least delay finishes first.
604-- When compared to imperative programming, this can be viewed as a @for@ loop
605-- with three concurrent iterations.
606--
607-- Concurrency is demand driven i.e. more concurrent iterations are started
608-- only if the previous iterations are not able to saturate the consumer of the
609-- output stream. This works exactly the same way as the merging of two
610-- streams using 'async' works.
611--
612-- The 'fromAsync' type combinator can be used to switch to this style of
613-- composition. Alternatively, a type annotation can be used to specify the
614-- type of the stream as 'Async'.
615--
616-- When multiple streams are nested using this style, the iterations are
617-- concurrently evaluated in a depth first manner:
618--
619--
620-- >>> :{
621-- Stream.drain $ Stream.fromAsync $ do
622-- x <- Stream.fromFoldable [1,2]
623-- y <- Stream.fromFoldable [3,4]
624-- Stream.fromEffect $ putStrLn $ show (x, y)
625-- :}
626-- (1,3)
627-- (1,4)
628-- (2,3)
629-- (2,4)
630--
631-- Nested iterations are given preference for concurrent evaluation i.e.
632-- (1,4) will be scheduled in preference to (2,3).
634-- $wasyncNesting
635--
636-- Like 'Async', the 'Monad' composition of 'WAsync' runs the iterations of a
637-- loop concurrently. It differs from 'Async' in the nested loop behavior. Like
638-- 'WSerial', the nested loops in this type are traversed and executed in a
639-- breadth first manner rather than the depth first manner of 'Async' style.
640--
641-- >>> :{
642-- Stream.drain $ Stream.fromWAsync $ do
643-- x <- Stream.fromSerial $ Stream.fromFoldable [1,2]
644-- y <- Stream.fromSerial $ Stream.fromFoldable [3,4]
645-- Stream.fromEffect $ putStrLn $ show (x, y)
646-- :}
647-- (1,3)
648-- (1,4)
649-- (2,3)
650-- (2,4)
651--
652-- Note that (2,3) is preferred to (1,4) when evaluating the iterations
653-- concurrently. This works exactly the same way as the merging of two streams
654-- using 'wAsync' works.
655--
656-- The 'fromWAsync' type combinator can be used to switch to this style of
657-- composition. Alternatively, a type annotation can be used to specify the
658-- type of the stream as 'WAsync'.
659--
661-- $parallelNesting
662--
663-- Just like 'Async' or 'WAsync' the 'Monad' composition of 'Parallel' runs the
664-- iterations of a loop concurrently.
665--
666-- >>> :{
667-- Stream.drain $ Stream.fromParallel $ do
668-- x <- Stream.fromFoldable [3,2,1]
669-- delay x
670-- :}
671-- ThreadId ...: Delay 1
672-- ThreadId ...: Delay 2
673-- ThreadId ...: Delay 3
674--
675-- It differs from 'Async' and 'WAsync' in the nested loop behavior. All
676-- iterations of the loop are run fully concurrently irrespective of the
677-- demand. This works exactly the same way as the merging of streams using
678-- 'parallel' works.
679--
680-- The 'fromParallel' type combinator can be used to switch to this style of
681-- composition. Alternatively, a type annotation can be used to specify the
682-- type of the stream as 'Parallel'.
683--
685-- $applicative
686--
687-- 'Async' can run the iterations concurrently, therefore, it takes a total
688-- of 6 seconds which is max (1, 2) + max (3, 4):
689--
690-- >>> (Stream.toList $ Stream.fromAsync $ (,) <$> s1 <*> s2) >>= print
691-- ...
692--
693-- @
694-- ThreadId 34: Delay 1
695-- ThreadId 36: Delay 2
696-- ThreadId 35: Delay 3
697-- ThreadId 36: Delay 3
698-- ThreadId 35: Delay 4
699-- ThreadId 36: Delay 4
700-- [(1,3),(2,3),(1,4),(2,4)]
701-- @
702--
703-- Similarly, 'WAsync' as well can run the iterations concurrently, but with a
704-- different style of scheduling than 'Async' as explained in the Monad
705-- section, therefore, it too takes a total of 6 seconds (2 + 4):
706--
707-- >>> (Stream.toList $ Stream.fromWAsync $ (,) <$> s1 <*> s2) >>= print
708-- ...
709--
710-- @
711-- ThreadId 34: Delay 1
712-- ThreadId 36: Delay 2
713-- ThreadId 35: Delay 3
714-- ThreadId 36: Delay 3
715-- ThreadId 35: Delay 4
716-- ThreadId 36: Delay 4
717-- [(1,3),(2,3),(1,4),(2,4)]
718-- @
720-- $parallelzip
721--
722-- The applicative instance of 'ZipAsync' type zips streams concurrently.
723-- 'fromZipAsync' type combinator can be used to switch to parallel applicative
724-- zip composition:
725--
726-- This takes 7 seconds to zip, which is max (1,3) + max (2,4) because 1 and 3
727-- are produced concurrently, and 2 and 4 are produced concurrently:
728--
729-- >>> d n = delay n >> return n
730-- >>> s1 = Stream.fromSerial $ d 1 <> d 2
731-- >>> s2 = Stream.fromSerial $ d 3 <> d 4
732-- >>> (Stream.toList $ Stream.fromZipAsync $ (,) <$> s1 <*> s2) >>= print
733-- ThreadId ...: Delay 1
734-- ThreadId ...: Delay 2
735-- ThreadId ...: Delay 3
736-- ThreadId ...: Delay 4
737-- [(1,3),(2,4)]
738--
740-- $concurrent
741--
742-- When writing concurrent programs there are two distinct places where the
743-- programmer can control the concurrency. First, when /composing/ a stream by
744-- merging multiple streams we can choose an appropriate sum style operators to
745-- combine them concurrently or serially. Second, when /processing/ a stream in
746-- a monadic composition we can choose one of the monad composition types to
747-- choose the desired type of concurrency.
748--
749-- In the following example the squares of @x@ and @y@ are computed
750-- concurrently using the 'async' operation and the square roots of their
751-- sum are computed serially because of the 'fromSerial' combinator. We can
752-- choose different combinators for the monadic processing and the stream
753-- generation, to control the concurrency. We can also use the 'fromAsync'
754-- combinator instead of explicitly folding with 'async'.
755--
756-- >>> import Data.List (sum)
757-- >>> :{
758-- main = do
759-- z <- Stream.toList
760-- $ Stream.fromSerial -- Serial monadic processing (sqrt below)
761-- $ do
762-- x2 <- Stream.concatForFoldableWith Stream.async [1..100] $ -- Concurrent @"for"@ loop
763-- \x -> return $ x * x -- body of the loop
764-- y2 <- Stream.concatForFoldableWith Stream.async [1..100] $
765-- \y -> return $ y * y
766-- return $ sqrt (x2 + y2)
767-- print $ sum z
768-- :}
769--
770-- We can see how this directly maps to the imperative style
771-- <https://en.wikipedia.org/wiki/OpenMP OpenMP> model, we use combinators
772-- and operators instead of the ugly pragmas.
773--
774-- For more concurrent programming examples see,
775-- <https://github.com/composewell/streamly-examples>.
777-- $furtherReading
778--
779-- * Read the reactive programming tutorial
780-- * See the examples in <https://github.com/composewell/streamly-examples streamly-examples> repo.