Forking I/O actions for concurrency
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 demonstrate simple input/output concurrently in Haskell. We will get the number of seconds to wait from the user input, and in the background, it will sleep and print a message once the thread wakes up.
How to do it…
- Import the built-in concurrency package as follows:
import Control.Concurrent (forkIO, threadDelay)
- Ask the user the number of seconds the program has to sleep for. Then, sleep for that many seconds by calling our
sleep
function defined in the following code snippet. Finally, recursively callmain
again to demonstrate that the user can continue to input while a thread is running in the background:main = do putStr "Enter number of seconds to sleep: " time <- fmap (read :: String -> Int) getLine forkIO $ sleep time main
- Define a function that takes...