英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论