Version 3 (modified by blamario, 5 years ago)

--

monad-parallel

The low-level libraries available with GHC provide two completely different ways to execute tasks in parallel: par and forkIO. The former can be applied to any pure computation, while the latter works only in the IO monad.

The purpose of the monad-parallel library package is to unify the two approaches. For this purpose, it defines classes of monads that are capable of:

  • splitting or forking monadic computations to be performed in parallel, and
  • combining the results of those computations when they complete.

The way these classes are implemented by the IO monad (as well as any MonadIO instance) is different from the way they're implemented by stateless monads, but the classes abstract these implementation details away.

Class MonadFork

A monad that's an instance of the MonadFork class supports method

 forkExec :: MonadFork m => m a -> m (m a)

This function launches the argument computation in a parallel thread and returns a handle to it. The main thread is free to perform some other task and then obtain the result of the parallel computation:

task1 :: Monad Int
task2 :: Monad Int
task3 :: Monad Int

example = do handle1 <- forkExec task1
             handle2 <- forkExec task2
             result3 <- task3
             result1 <- handle1
             result2 <- handle2
             return (result1 + result2 + result3)

Class MonadParallel

A monad that's an instance of the MonadParallel class supports method

 bindM2 :: MonadParallel m => (a -> b -> m c) -> m a -> m b -> m c