A quick and easy way to launch an I/O type function in the background is by calling the forkIO
function provided by the Control.Concurrent
package. In this recipe, we will be communicating with forked I/O actions by sending messages using a variable type called
MVar
.
Import the relevant packages as follows:
import Network.HTTP import Control.Concurrent
Create a new variable that will be used by the fork process. The
newEmptyMVar
function is of theIO (MVar a)
type, so we will extract the expression out and label itm
as follows:main = do m <- newEmptyMVar forkIO $ process m
After running the fork, send it some data by calling
putMVar :: MVar a -> a -> IO ()
, as shown in the following lines of code. The variable will hold the given value, and the forked process waiting on that data will resume:putStrLn "sending first website..." putMVar m "http...