os.File的Write()方法是线程安全的吗?

huangapple go评论100阅读模式
英文:

Is os.File's Write() threadsafe?

问题

我想知道在 os.File 上调用 Write() 方法是否是线程安全的。我在文档中很难找到有关线程安全性的任何提及。

英文:

I was wondering if calling Write() on an os.File is thread safe. I'm having a hard time finding any mention of thread safety in the docs.

答案1

得分: 12

标准库的约定(至少对于标准库而言)如下:除非明确声明(或从上下文中明显),否则没有任何函数/方法可以安全地并发使用。

在没有外部同步的情况下,通过Write()并发写入os.File是不安全的。

英文:

The convention (at least for the standard library) is the following: No function/method is safe for concurrent use unless explicitly stated (or obvious from the context).

It is not safe to write concurrently to an os.File via Write() without external synchronization.

答案2

得分: 1

在浏览了一小部分源代码后,我发现了以下方法,最终由file.Write()调用。由于存在竞争条件检查,我认为在Go中该调用实际上不是线程安全的(来源)。

然而,这些系统调用在操作系统级别上应该是线程安全的,这似乎不太可能。在浏览了一些内容后,我发现了这个有趣的答案,更加加深了我的怀疑。对于Windows,源代码指示调用WriteFile,它似乎也是线程安全的。

英文:

After browsing the source code a little bit I found the following method which is eventually called by file.Write(). Since there are race condition checks in place, I'm assuming that the call is in fact not thread-safe within Go (Source).

However, it seemed unlikely that those system calls wouldn't be thread-safe on an OS level. After some browsing I came upon this interesting answer that fueled my suspicions even more. For windows the source indicates a call to WriteFile which also appears to be thread safe.

huangapple
  • 本文由 发表于 2015年6月10日 10:39:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/30746166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定