Execution order with (>>=) not what I expected

风格不统一 提交于 2019-12-08 16:11:57

问题


I've got a series of network requests, that each take >10 seconds.
So that the user knows what's happening, I give updates:

main = do putStr "Downloading the first thing... "
          {- Net request -}
          putStrLn "DONE"
          putStr "Downloading the second thing... "
          {- Net request -}
          putStrLn "DONE"

With GHCi this works as expected, but compiled or with runghc, "Downloading" doesn't print till "DONE" does.

I've rewritten it with (>>=) and (>>), but I get the same problem.

What's going on?


回答1:


The problem here isn't with the execution order. The statements execute in exactly the order you expect. The problem is that due to buffering, you don't actually see the results as soon as they happen.

Specifically terminal IO is line-buffered by default. This means that no output will appear on the screen until you print a newline or flush the buffer. So you need to either flush the´output stream using hFlush after executing putStr or you need to change stdout's buffering mode using hSetBuffering to not use line buffering.



来源:https://stackoverflow.com/questions/8361508/execution-order-with-not-what-i-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!