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.
write() is certainly thread-safe. The problem is that a partial write() could require multiple calls in order to completely write the data, and while that is "thread-safe" it could result in interleaved data.
Writing to File is Not Thread-Safe A best practice is to open a file using the context manager interface so that the file is closed automatically once any writing operations are finished. Writing to the same file from multiple threads concurrently is not thread safe and may result in a race condition.
Any system level (syscall) file descriptor access is thread safe in all mainstream UNIX-like OSes.
fopen(), fdopen() and freopen() are thread-safe. These interfaces are not async-cancel-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With