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.
2 Answers
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.

- 40,468
- 7
- 81
- 87
-
1Thanks! Do you have a pointer to any place that the convention is mentioned? – Gabe Jun 10 '15 at 03:45
-
No, sorry. I think this is just a convention. – Volker Jun 10 '15 at 05:19
-
for those who encounter this question, you can see in go 1.16 that `fd.writeLock();` is used in `Write(buf []byte)` function, so it seems that it uses internal synchronization – Sobhan Atar Oct 13 '21 at 19:53
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.