putStrLn是线程安全的吗? [英] Is putStrLn thread-safe?

查看:131
本文介绍了putStrLn是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果我有多个调用 putStrLn 的线程,而没有任何并发​​控制,线程的输出可能会被交织。



我的问题是 putStrLn 是否是线程安全的模数交错输出?

I假设 putStrLn 是一个缓冲写入操作,所以我真的在问是否有两个线程调用 putStrLn



一般来说,关于Haskell(真正的GHC)的其他标准I / O功能?特别是,对于任何缓冲读取操作,是否可以让同一个字符返回到两个不同的线程,同时进行相同的读取调用?

解决方案

是的,从问题的角度来看,它是线程安全的。 Handle MVar 保护,这将不允许缓冲区被破坏。正如你指出的那样,交错是另外一回事。

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?

解决方案

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.

这篇关于putStrLn是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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