ErikR
ErikR

Reputation: 52067

Is putStrLn thread-safe?

I know that if I have multiple threads calling putStrLn without any kind of concurrency control that the output of the threads may be interleaved.

My question is whether putStrLn is thread-safe modulo this interleaved output?

I am presuming that putStrLn is a buffered write operation, so I'm really asking if any corruption of the output buffer can occur by having two threads call putStrLn at the same time.

And in general, what can be said about the thread safety of Haskell's (really GHC's) other "standard I/O" functions? In particular, for any of the buffered read operations is it possible for the same character to get returned to two different threads making the same read call at the same time?

Upvotes: 30

Views: 1030

Answers (1)

shachaf
shachaf

Reputation: 8930

Yes, it's thread-safe in the sense that you're asking about. A Handle is protected by an MVar which won't allow the buffer to become corrupted. As you pointed out, though, interleaving is a different matter.

Upvotes: 28

Related Questions