Add API to gather results of multiple computations

This commit is contained in:
Harendra Kumar 2017-06-29 05:40:29 +05:30
parent afbd289a89
commit 120d0ed5f0
3 changed files with 23 additions and 0 deletions

View File

@ -16,6 +16,7 @@ module Strands
, async
, waitEvents
, each
, gather
, sample
, threads
, logged

View File

@ -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
View 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