Book Image

Haskell Data Analysis Cookbook

By : Nishant Shukla
Book Image

Haskell Data Analysis Cookbook

By: Nishant Shukla

Overview of this book

Table of Contents (19 chapters)
Haskell Data Analysis Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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…

  1. Import the built-in concurrency package as follows:

    import Control.Concurrent (forkIO, threadDelay)
  2. 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 call main 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
  3. Define a function that takes in the number of...