本文介绍了多个线程对同一文件写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果我们可以使用多个线程写在同一个文件的二进制数据。

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 = sizeof(sizeof(int) * SIZE);
// .. filling the table
fwrite(table, sizeof(*table), SIZE, fd);

所以我不知道如果我能使用线程,每个线程调用fssek寻求到不同的位置在同一文件中写入。

so I wonder if i can use threads,and each thread calls fssek to seek to a different location to write in the same file.

任何想法?

推荐答案

FREAD()的fwrite()是线程安全的,由 FILE * 不是。所以,你可以有多个线程访问同一个文件,而不是通过同一 FILE * - 每个线程都必须有它自己的,以及它们所引用必须是共享的文件 - 这取决于操作系统。

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.

的替代,可能更简单的方法是使用一个,以便每个线程将文件处理为共享内存,并且让操作系统处理文件I / O。这已超过正常文件显著优势,I / O,因为它是真正的随机访问,所以您不必担心 fseek的()和顺序读/写等。

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.

这篇关于多个线程对同一文件写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 06:52
查看更多