mirror of
https://github.com/ilyakooo0/streamly.git
synced 2024-10-06 21:27:35 +03:00
Add API to gather results of multiple computations
This commit is contained in:
parent
afbd289a89
commit
120d0ed5f0
@ -16,6 +16,7 @@ module Strands
|
||||
, async
|
||||
, waitEvents
|
||||
, each
|
||||
, gather
|
||||
, sample
|
||||
, threads
|
||||
, logged
|
||||
|
@ -8,6 +8,7 @@ module Strands.Threads
|
||||
, each
|
||||
, sample
|
||||
, sync
|
||||
, gather
|
||||
--, react
|
||||
, threads
|
||||
|
||||
@ -537,6 +538,13 @@ gatherResult ref r = do
|
||||
liftIO $ atomicModifyIORef ref $ \rs -> (r : rs, ())
|
||||
mzero
|
||||
|
||||
gather :: (MonadIO m, MonadCatch m) => AsyncT m a -> AsyncT m [a]
|
||||
gather m = AsyncT $ do
|
||||
resultsRef <- liftIO $ newIORef []
|
||||
lift $ waitAsync (gatherResult resultsRef) Nothing m
|
||||
r <- liftIO $ readIORef resultsRef
|
||||
return $ Just r
|
||||
|
||||
-- | Run an 'AsyncT m' computation and collect the results generated by each
|
||||
-- thread of the computation in a list.
|
||||
wait :: (MonadIO m, MonadCatch m) => AsyncT m a -> m [a]
|
||||
|
14
test/gather.hs
Normal file
14
test/gather.hs
Normal file
@ -0,0 +1,14 @@
|
||||
import Control.Concurrent (threadDelay, myThreadId)
|
||||
import Control.Monad.IO.Class (liftIO)
|
||||
import System.Random (randomIO)
|
||||
import System.IO
|
||||
|
||||
import Strands
|
||||
|
||||
--- Check space leaks
|
||||
|
||||
main = do
|
||||
x <- wait $ do
|
||||
y <- gather $ each [1..10]
|
||||
liftIO $ print y
|
||||
print x
|
Loading…
Reference in New Issue
Block a user