Is ofstream thread safe?

后端 未结 3 1047
你的背包
你的背包 2020-12-10 19:00

I am working on a program, which uses multiple std::ifstreams for reading a binary file, one std::ifstream for each thread. Now I need to know, if

相关标签:
3条回答
  • 2020-12-10 19:22

    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.

    0 讨论(0)
  • 2020-12-10 19:32

    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].

    0 讨论(0)
  • 2020-12-10 19:43

    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.

    0 讨论(0)
提交回复
热议问题