Thursday, December 9, 2010

parallel-io

A few days ago, parallel-io was uploaded to Hackage. Previously, when I wanted to perform a number of I/O actions in parallel, I used some homegrown code that used forkIO and MVar's to run a bunch of I/O actions in parallel and collect their result.

The new package makes all that unnecessary. Its two most important functions functions are:

    parallel_ :: [IO a] -> IO ()  -- ignores results
    parallel  :: [IO a] -> IO [a] -- collects results into a list
I have some code that fetches a number of exchange rates in relation to the US dollar. I want to do this work in parallel, so previously I used my own combinators. Now it's as simple as:
    getExchangeRateToUSD :: String -> IO Double
    getExchangeRateToUSD = ...

    parallel $ map getExchangeRateToUSD ["CAD", "EUR", "JPY", "GBP"]
The map call returns a list of IO actions. parallel-io dutifully forks off a thread for each of these actions and returns a value of type IO [Double]. Nice and simple.

No comments:

Post a Comment