Context Navigation

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:

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

This method executes its m a and m b arguments in parallel. Once they're both finished, bindM2 runs their results through its first argument and returns the final result. Note that 'bindM2' can be implemented using forkExec, but not vice versa.

Based on this foundation, the library defines and exports other useful functions. These replicate the functionality of the Control.Monad module, but they execute their monadic arguments in parallel.