1{-# OPTIONS_GHC -fno-warn-unused-imports #-}
3-- Module : ConcurrentStreams
4-- Copyright : (c) 2017 Composewell Technologies
7-- Maintainer : streamly@composewell.com
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
15 -- * Concurrent Streams
18 -- * Combining Streams
21 -- * Imports and Supporting Code
24 -- * Generating Streams Concurrently
25 -- $generatingConcurrently
27 -- * Concurrent Pipeline Stages
28 -- $concurrentApplication
30 -- * Mapping Concurrently
31 -- $concurrentTransformation
37 -- *** Deep Speculative Composition ('Ahead')
40 -- *** Deep Asynchronous Composition ('Async')
43 -- *** Wide Asynchronous Composition ('WAsync')
46 -- *** Parallel Asynchronous Composition ('Parallel')
49 -- XXX we should deprecate and remove the mkAsync API
59 -- *** Deep Speculative Nesting ('Ahead')
62 -- *** Deep Asynchronous Nesting ('Async')
65 -- *** Wide Asynchronous Nesting ('WAsync')
68 -- *** Parallel Asynchronous Nesting ('Parallel')
76 -- ** Parallel Zipping
79 -- * Concurrent Programming
82 -- * Writing Concurrent Programs
85 -- * Where to go next?
90import Streamly.Prelude
92import Control.Applicative
94import Control.Monad.IO.Class (MonadIO(..))
95import Control.Monad.Trans.Class (MonadTrans (lift))
97-- CAUTION: please keep setup and imports sections in sync
101-- >>> import Data.Function ((&))
102-- >>> import Streamly.Prelude ((|:), (|&))
103-- >>> import qualified Streamly.Prelude as Stream
104-- >>> import qualified Streamly.Data.Fold as Fold
106-- >>> import Control.Concurrent (threadDelay, myThreadId)
108-- delay n = Stream.fromEffect $ do
109-- threadDelay (n * 1000000)
111-- putStrLn (show tid ++ ": Delay " ++ show n)
114-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
115-- >>> hSetBuffering stdout LineBuffering
120-- In most of example snippets we do not repeat the imports. Where imports are
121-- not explicitly specified use the imports shown below.
124-- >>> import Data.Function ((&))
125-- >>> import Streamly.Prelude ((|:), (|&))
126-- >>> import qualified Streamly.Prelude as Stream
127-- >>> import qualified Streamly.Data.Fold as Fold
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.
133-- >>> import Control.Concurrent (threadDelay, myThreadId)
135-- delay n = Stream.fromEffect $ do
136-- threadDelay (n * 1000000)
138-- putStrLn (show tid ++ ": Delay " ++ show n)
141-- For concurrent examples, use line buffering, otherwise output from different
142-- threads may get mixed:
144-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
145-- >>> hSetBuffering stdout LineBuffering
150-- Many stream operations can be done concurrently:
152-- * Streams can be generated concurrently.
154-- * Streams can be merged concurrently.
156-- * Multiple stages in a streaming pipeline can run concurrently.
158-- * Streams can be mapped and zipped concurrently.
160-- * In monadic composition they combine like a list transformer,
161-- providing concurrent non-determinism.
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.
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.
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-- +------------+--------------+--------------+--------------+
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.
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.
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
225-- +------------+-----------+
227-- +============+===========+
228-- | 'Serial' | 'WSerial' |
229-- +------------+-----------+
230-- | 'Ahead' | 'WAhead' |
231-- +------------+-----------+
232-- | 'Async' | 'WAsync' |
233-- +------------+-----------+
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.
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
260-- $generatingConcurrently
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.
269-- The following code finishes in 3 seconds (6 seconds when serial):
271-- >>> let p n = threadDelay (n * 1000000) >> return n
272-- >>> Stream.toList $ Stream.fromParallel $ p 3 |: p 2 |: p 1 |: Stream.nil
275-- >>> Stream.toList $ Stream.fromAhead $ p 3 |: p 2 |: p 1 |: Stream.nil
278-- The following finishes in 10 seconds (100 seconds when serial):
280-- >>> Stream.drain $ Stream.fromAsync $ Stream.replicateM 10 $ p 10
283-- $concurrentTransformation
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.
290-- This would print a value every second (2 seconds when serial):
292-- >>> let p n = threadDelay (n * 1000000) >> return n
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
303-- $concurrentApplication
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:
309-- Because both the stages run concurrently, we would see a delay of only 1
310-- second instead of 2 seconds in the following:
312-- >>> let p n = threadDelay (n * 1000000) >> return n
315-- Stream.repeatM (p 1)
316-- |& Stream.mapM (\x -> p 1 >> print x)
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.
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:
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
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.
346-- You can also use the polymorphic combinator 'ahead' in place of '<>' to
347-- compose any type of streams in this manner.
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
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:
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
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:
380-- >>> p n = threadDelay 1000000 >> return n
381-- >>> stream = (Stream.fromSerial stream1) <> (Stream.fromSerial stream2)
382-- >>> Stream.toList $ Stream.fromAsync stream
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:
390-- >>> Stream.drain $ Stream.fromAsync $ delay 3 <> delay 2 <> delay 1
391-- ThreadId ...: Delay 1
392-- ThreadId ...: Delay 2
393-- ThreadId ...: Delay 3
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.
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
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:
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
424-- Note that the order of printing in the above examples may change due to
425-- variations in scheduling latencies for concurrent threads.
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:
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
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
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
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.
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
468-- In the following example we can see that outputs are produced in the breadth
469-- first traversal order but this is not guaranteed.
471-- >>> stream1 = print 1 |: print 2 |: Stream.nil
472-- >>> stream2 = print 3 |: print 4 |: Stream.nil
473-- >>> Stream.drain $ Stream.fromWAsync $ stream1 <> stream2
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:
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
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
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.
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.
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:
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
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.
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>.
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
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
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
562-- Stream.toList $ Stream.fromAhead $ do
563-- x <- Stream.fromFoldable [3,2,1]
567-- ThreadId ...: Delay 1
568-- ThreadId ...: Delay 2
569-- ThreadId ...: Delay 3
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.
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.
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'.
589-- The 'Monad' composition of 'Async' type can perform the iterations of a
593-- Stream.drain $ Stream.fromAsync $ do
594-- x <- Stream.fromFoldable [3,2,1]
597-- ThreadId ...: Delay 1
598-- ThreadId ...: Delay 2
599-- ThreadId ...: Delay 3
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.
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.
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'.
616-- When multiple streams are nested using this style, the iterations are
617-- concurrently evaluated in a depth first manner:
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)
631-- Nested iterations are given preference for concurrent evaluation i.e.
632-- (1,4) will be scheduled in preference to (2,3).
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.
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)
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.
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'.
663-- Just like 'Async' or 'WAsync' the 'Monad' composition of 'Parallel' runs the
664-- iterations of a loop concurrently.
667-- Stream.drain $ Stream.fromParallel $ do
668-- x <- Stream.fromFoldable [3,2,1]
671-- ThreadId ...: Delay 1
672-- ThreadId ...: Delay 2
673-- ThreadId ...: Delay 3
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
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'.
687-- 'Async' can run the iterations concurrently, therefore, it takes a total
688-- of 6 seconds which is max (1, 2) + max (3, 4):
690-- >>> (Stream.toList $ Stream.fromAsync $ (,) <$> s1 <*> s2) >>= print
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)]
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):
707-- >>> (Stream.toList $ Stream.fromWAsync $ (,) <$> s1 <*> s2) >>= print
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)]
722-- The applicative instance of 'ZipAsync' type zips streams concurrently.
723-- 'fromZipAsync' type combinator can be used to switch to parallel applicative
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:
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
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.
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'.
756-- >>> import Data.List (sum)
760-- $ Stream.fromSerial -- Serial monadic processing (sqrt below)
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)
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.
774-- For more concurrent programming examples see,
775-- <https://github.com/composewell/streamly-examples>.
779-- * Read the reactive programming tutorial
780-- * See the examples in <https://github.com/composewell/streamly-examples streamly-examples> repo.
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