问题描述
我很难在Haskell中创建一些基本内容.
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.
我认为我应该使用forkIO,但是我不确定如何构造该语句.
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
推荐答案
首先:您的想法是正确的-您可以使用 forkIO
-您可以用来让线程休眠一段时间的函数是 threadDelay
(您必须使用 micro seconds!-通常只有 milli seconds,所以请当心)
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)
最简单的方法是将forkIO
正确地嵌入到您的计算中(此处为main
)-以下是一个简短的代码段,可按您的要求进行操作:
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 ()
如果使用-threaded
进行编译:
ghc Main.hs -threaded
如果应该打印第一行,然后等待5秒钟.最后打印第二行.
if should print the first line then wait 5sec. and finally print the second line.
- 最后一个
getLine
是穷人,在那里等待线程-因此,您必须按 结束程序(如果没有,将不会有输出因为程序以主线程结束) -
threadId
是 启动的线程的c7> -查看Control.Concurrent
模块,以了解与之交互的一些方法
- 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 theThreadId
of the thread you just started - have a look at theControl.Concurrent
module to see some ways to interact with that
也许您不希望在main
内部使用它-如果这样,您也可以将其重构(这可能会产生更简洁的代码):
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"
这篇关于Haskell-创建线程,写入屏幕,休眠线程,向屏幕写入其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!