2012-07-18 23:25:46 +00:00
|
|
|
{- parallel processing via threads
|
2012-06-22 19:46:21 +00:00
|
|
|
-
|
|
|
|
- Copyright 2012 Joey Hess <joey@kitenet.net>
|
|
|
|
-
|
2014-05-10 14:01:27 +00:00
|
|
|
- License: BSD-2-clause
|
2012-06-22 19:46:21 +00:00
|
|
|
-}
|
|
|
|
|
|
|
|
module Utility.Parallel where
|
|
|
|
|
|
|
|
import Common
|
|
|
|
|
2012-07-18 23:25:46 +00:00
|
|
|
import Control.Concurrent
|
2012-07-18 22:29:33 +00:00
|
|
|
|
2012-07-18 23:25:46 +00:00
|
|
|
{- Runs an action in parallel with a set of values, in a set of threads.
|
|
|
|
- In order for the actions to truely run in parallel, requires GHC's
|
|
|
|
- threaded runtime,
|
|
|
|
-
|
2012-06-26 21:33:34 +00:00
|
|
|
- Returns the values partitioned into ones with which the action succeeded,
|
|
|
|
- and ones with which it failed. -}
|
2012-07-30 15:52:44 +00:00
|
|
|
inParallel :: (v -> IO Bool) -> [v] -> IO ([v], [v])
|
2012-06-23 05:33:10 +00:00
|
|
|
inParallel a l = do
|
2012-07-18 23:25:46 +00:00
|
|
|
mvars <- mapM thread l
|
|
|
|
statuses <- mapM takeMVar mvars
|
|
|
|
return $ reduce $ partition snd $ zip l statuses
|
2012-12-13 04:24:19 +00:00
|
|
|
where
|
|
|
|
reduce (x,y) = (map fst x, map fst y)
|
|
|
|
thread v = do
|
|
|
|
mvar <- newEmptyMVar
|
|
|
|
_ <- forkIO $ do
|
|
|
|
r <- try (a v) :: IO (Either SomeException Bool)
|
|
|
|
case r of
|
|
|
|
Left _ -> putMVar mvar False
|
|
|
|
Right b -> putMVar mvar b
|
|
|
|
return mvar
|