是阅读和不同的字节范围线程安全写入同一个文件? [英] Is reading and writing to the same file at different bytes-range thread-safe?
问题描述
我有一个文件名为data.txt中总是与50个字节的数据。
I have one file named "data.txt" with always 50 bytes of data.
我有两个线程。
第一个线程,读取字节0到字节50的内容:
The first thread, read content from byte 0 to byte 50:
while(1){
char buf[50];
FILE* fp = fopen("data.txt","r");
fread(buf,1,50,fp);
/* process data */
fclose(fp);
}
第二个线程,将数据追加到文件(=总是第一个50字节后):
The second thread, append data to the file (= always after the first 50 bytes):
while(1){
FILE* fp = fopen("data.txt","a");
fwrite("hello\n",1,6,fp);
fclose(fp);
}
这是解决方案的线程安全和便携? (不分段错误,数据不一致,...)
Is this solution thread-safe and portable ? (no segmentation fault, no data inconsistency, ...)
推荐答案
我在你的其他相关岗位写的,我所知应该不会崩溃。无论是写入和读取,读取正确我不知道。
As I wrote in your other, related post, to my best knowledge it shouldn't crash. Whether it writes and reads and reads properly I don't know.
如果你是一个POSIX系统上:你有没有使用FIFO(见的 http://man7.org/linux/man-pages/man7/fifo.7.html )?我有IM pression文件系统是只为你的基础通信需求的一个帮手,即实际的文件并不重要。
If you are on a POSIX system: Have you considered using a fifo (cf. http://man7.org/linux/man-pages/man7/fifo.7.html)? I have the impression that the file system is just a helper for your underlying communication demand, i.e. the actual file is not important.
这篇关于是阅读和不同的字节范围线程安全写入同一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!