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
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.
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 thatMaybe 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With