Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 871
amindfv Avatar asked Dec 02 '11 19:12

amindfv


1 Answers

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.

like image 178
sepp2k Avatar answered Oct 20 '22 21:10

sepp2k