Multiple threads writing on same file

前端 未结 4 712
说谎
说谎 2020-12-21 10:41

I would like to know if we can use multiple threads to write binary data on the same file.

FILE *fd = openfile(\"test\");
int SIZE = 1000000000;
int * table          


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-21 11:23

    While fread() and fwrite() are thread safe, the stream buffer represented by the FILE* is not. So you can have multiple threads accessing the same file, but not via the same FILE* - each thread must have its own, and the file to which they refer must be shareable - which is OS dependent.

    An alternative and possibly simpler approach is to use a memory mapped file, so that each thread treats the file as shared memory, and you let the OS deal with the file I/O. This has a significant advantage over normal file I/O as it is truly random access, so you don't need to worry about fseek() and sequential read/writes etc.

提交回复
热议问题