[Haskell-cafe] Parallel executing of actions

Spencer Janssen sjanssen at cse.unl.edu
Sun Apr 15 15:23:58 EDT 2007

On Sun, 15 Apr 2007 18:01:44 +0200
Mitar <mmitar at gmail.com> wrote:

> Hi!
> Is there a parallel version of mapM_? Like it is for map (parMap)?

This version will fork a new thread for each action:

import Control.Concurrent
import Control.Monad

parSequence_ xs = do
    m <- newEmptyMVar
    mapM_ (\x -> forkIO x >> putMVar m ()) xs
    replicateM_ (length xs) (takeMVar m)

parMapM_ f xs = parSequence_ $ map f xs

> I would like to execute actions in parallel as the computation of
> necessary data for actions is quite computational heavy. But it does
> not matter in which order those actions are executed. (I am rendering
> pixels with OpenGL and it does not matter in which order I draw them,
> but it matters that for one pixel it takes some time to calculate its
> color.)
> The example would be:
> main :: IO ()
> main = do
>   -- the order of printed characters is not important
>   -- instead of putStrLn there will be a computationally big function
>   -- so it would be great if those computations would be done in
> parallel -- and results printed out as they come
>   mapM_ rwhnf (putStrLn) ["a","b","c","d"]
> Is this possible? Without unsafe functions? And without changing the
> semantics of the program.

Of course the semantics of the program will change, the order in which
the actions are executed is unknown!

Spencer Janssen

More information about the Haskell-Cafe mailing list