July 2013
Intermediate to advanced
322 pages
8h 43m
English
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->IOByteString
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
importControl.ConcurrentimportData.ByteStringasBimportGetURLmain=dom1<-newEmptyMVar--![]()
m2<-newEmptyMVar--![]()
forkIO$do--![]()
r<-getURL"http://www.wikipedia.org/wiki/Shovel"putMVarm1rforkIO$do--![]()
r<-getURL"http://www.wikipedia.org/wiki/Spade"putMVarm2rr1<-takeMVarm1--![]()
r2<-takeMVarm2--(B.lengthr1,B.lengthr2)--
Create two new empty MVar