Skip to Main Content
Parallel and Concurrent Programming in Haskell
book

Parallel and Concurrent Programming in Haskell

by Simon Marlow
July 2013
Intermediate to advanced content levelIntermediate to advanced
322 pages
8h 43m
English
O'Reilly Media, Inc.
Content preview from Parallel and Concurrent Programming in Haskell

Chapter 8. Overlapping Input/Output

We can use MVar and threads to do asynchronous I/O, where “asynchronous” in this context means that the I/O is performed in the background while we do other tasks.

Suppose we want to download some web pages concurrently and wait for them all to download before continuing. We will use the following function to download a web page:

getURL :: String -> IO ByteString

This function is provided by the module GetURL in GetURL.hs, which is a small wrapper around the API provided by the HTTP package.

Let’s use forkIO and MVar to download two web pages at the same time:

geturls1.hs

import Control.Concurrent
import Data.ByteString as B
import GetURL

main = do
  m1 <- newEmptyMVar                                    -- 1
  m2 <- newEmptyMVar                                    -- 2

  forkIO $ do                                           -- 3
    r <- getURL "http://www.wikipedia.org/wiki/Shovel"
    putMVar m1 r

  forkIO $ do                                           -- 4
    r <- getURL "http://www.wikipedia.org/wiki/Spade"
    putMVar m2 r

  r1 <- takeMVar m1                                     -- 5
  r2 <- takeMVar m2                                     -- 
  print (B.length r1, B.length r2)                      -- 

Create two new empty MVar

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Haskell High Performance Programming

Haskell High Performance Programming

Samuli Thomasson
Haskell Cookbook

Haskell Cookbook

Yogesh Sajanikar
Haskell in Depth

Haskell in Depth

Vitaly Bragilevsky

Publisher Resources

ISBN: 9781449335939Supplemental ContentErrata Page