Is ofstream thread safe? Is ofstream thread safe? multithreading multithreading

Is ofstream thread safe?


If I haven't misunderstood you - no, nothing in the standard library is thread safe (except the std::thread specific things, of course (from C++11 and later)). You need additional synchronization.

Even more - if there are several processes, reading from/writing to these files, you need to lock the files, to sync the access.


From C++ standards (Input/Output Library Thread Safety):

27.1.3 Thread safety [iostreams.thread-safety]

Concurrent access to a stream object [string.streams, file.streams], stream buffer object [stream.buffers], or C Library stream [c.files] by multiple threads may result in a data race [intro.multithread] unless otherwise specified [iostream.objects]. [Note: Data races result in undefined behavior [intro.multithread].


Yes. It is.

For Windows:it is safe to write to fstream from multiple threads on windows. Please see the msdn document: Thread Safety in the C++ Standard Library

For Linux:In short, it is. From the document of libstdc++: "if your platform's C library is threadsafe, then your fstream I/O operations will be threadsafe at the lowest level". Is your platform's C library threadsafe? Yes. The POSIX standard requires that C stdio FILE* operations(such as fread/fwrite) are atomic, and glibc did so.