Haskell-创建线程,写入屏幕,休眠线程,向屏幕写入其他内容 [英] Haskell - Create thread, write to screen, sleep thread, write something else to screen

查看:94
本文介绍了Haskell-创建线程,写入屏幕,休眠线程,向屏幕写入其他内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在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

推荐答案

首先:您的想法是正确的-您可以使用

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.

  • 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

也许您不希望在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-创建线程,写入屏幕,休眠线程,向屏幕写入其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆