gpt4 book ai didi

c++ - 我们是否需要互斥量来执行多线程文件 IO

转载 作者:行者123 更新时间:2023-11-27 23:47:34 25 4
gpt4 key购买 nike

我正在尝试使用多线程 (pthread) 对文件进行随机写入(基准测试)。看起来如果我注释掉 mutex lock 创建的文件大小小于实际大小,好像有些写入正在丢失(总是以 block 大小的倍数)。但如果我保留互斥体,它总是精确的大小。

我的代码在其他地方有问题吗,实际上不需要互斥锁(@evan 的 as suggested)或者这里需要互斥锁

void *DiskWorker(void *threadarg) {

FILE *theFile = fopen(fileToWrite, "a+");
....
for (long i = 0; i < noOfWrites; ++i) {
//pthread_mutex_lock (&mutexsum);
// For Random access

fseek ( theFile , randomArray[i] * chunkSize , SEEK_SET );
fputs ( data , theFile );

//Or for sequential access (in this case above 2 lines would not be here)

fprintf(theFile, "%s", data);
//sequential access end

fflush (theFile);
//pthread_mutex_unlock(&mutexsum);
}
.....
}

最佳答案

您正在使用“追加模式”打开文件。根据 C11:

Opening a file with append mode ('a' as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function.

C 标准没有指定具体应该如何实现,但是在 POSIX 系统上,这通常使用 openO_APPEND 标志来实现。函数,而刷新数据是使用函数 write 完成的。请注意,您代码中的 fseek 调用应该没有任何效果。

我认为 POSIX 需要这个,因为它描述了 the shell 是如何在追加模式 (>>>) 中重定向输出的:

Appended output redirection shall cause the file whose name results from the expansion of word to be opened for output on the designated file descriptor. The file is opened as if the open() function as defined in the System Interfaces volume of POSIX.1-2008 was called with the O_APPEND flag. If the file does not exist, it shall be created.

而且由于大多数程序使用 FILE 接口(interface)将数据发送到 stdout,这可能需要 fopen 来使用在写入数据时使用 O_APPENDwrite(而不是像 pwrite 那样的函数)open

因此,如果在您的系统上使用 'a' 模式的 fopen 使用 O_APPEND 并且使用 write 完成刷新并且您的内核和文件系统正确地实现了 O_APPEND 标志,使用互斥体应该没有任何效果,因为写 do not intervene :

If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation.

请注意,并非所有文件系统都支持此行为。检查this回答。


至于我对您之前问题的回答,我的建议是删除互斥锁,因为它对文件的大小应该没有影响(而且它对我的机器没有任何影响)。

就我个人而言,我从未真正使用过 O_APPEND 并且会犹豫是否这样做,因为它的行为可能在某种程度上不受支持,而且它的行为在 Linux 上很奇怪(请参阅“错误”部分pwrite ).

关于c++ - 我们是否需要互斥量来执行多线程文件 IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49377419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com