Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Create thread, write to screen, sleep thread, write something else to screen

I'm having difficulty creating something basic in Haskell.

I'm trying to create new thread and write something to the screen, sleep, then write something else to the screen.

I think i'm supposed to be using the forkIO but i'm unsure how to structure the statement.

Thanks in advance to anyone who could help

like image 220
John Appleseed Avatar asked Dec 05 '25 10:12

John Appleseed


1 Answers

First: your idea is right - you can do this with forkIO - the function you can use to let your thread sleep for a while is threadDelay (you have to use microseconds! - usually it's only milliseconds, so watch out)

The easiest way is to embed the forkIO right into your computation (main here) - Here is a quick snippet that will do as you ask:

module Main where

import Control.Concurrent

main :: IO ()
main = do
  putStrLn "press Enter to exit the program"
  threadId <- forkIO $ do
    putStrLn "Something"
    threadDelay 5000000 -- wait 5 seconds
    putStrLn "Something Else"
  _ <- getLine
  return ()

if you compile this with -threaded:

ghc Main.hs -threaded

if should print the first line then wait 5sec. and finally print the second line.

remarks

  • The last getLine is there as a poor mans wait for the thread - so you have to end the program by pressing (without this there would be no output as the program ends with the main thread)
  • threadId is the ThreadId of the thread you just started - have a look at the Control.Concurrent module to see some ways to interact with that

Maybe you don't like to have this inside main - if so you can just refactor it out too (this might yield cleaner code):

main :: IO ()
main = do
  putStrLn "press Enter to exit the program"
  threadId <- forkIO myThreadComputation
  _ <- getLine
  return ()

myThreadComputation :: IO ()
myThreadComputation = do
    putStrLn "Something"
    threadDelay 5000000 -- wait 5 seconds
    putStrLn "Something Else"
like image 99
Random Dev Avatar answered Dec 08 '25 01:12

Random Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!