fopen()是Linux中的线程安全函数吗? [英] Is fopen() a thread safe function in Linux?

查看:516
本文介绍了fopen()是Linux中的线程安全函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用fopen()调用在多线程中打开同一文件,然后将数据写入该文件.我应该使用互斥锁来确保数据不会混乱吗?

If I use fopen() call to open a same file in multi-thread, and write data to the file. Should I use a mutex to ensure the data won't be disordered?

推荐答案

如果两个线程都使用fopen()打开同一文件,则它们各自将具有独立的文件流(FILE *),该文件流由独立的文件描述符支持,该文件描述符引用了相同的文件.您可以独立地写入两个文件流,但是文件的最终结果将取决于线程在何处写入以及何时刷新文件流.除非您控制每个线程的写入位置,否则结果是不可预测的.最简单的事情是确保两个线程使用相同的文件流,但是您可能仍需要在线程之间进行协调.请注意,POSIX需要C函数来提供对文件流的协调访问—请参见 flockfile() 强制要求

If two threads both open the same file with fopen(), they will each have independent file streams (FILE *) backed by independent file descriptors referring to the same file. You can write independently to the two file streams, but the net result on the file will depend on where the threads write and when they flush the file stream. The results are unpredictable unless you control where each thread is writing. The simplest thing is to make sure both threads use the same file stream, but you probably still need to coordinate between the threads. Note that POSIX requires the C functions to give coordinated access to the file stream — see flockfile() which imposes the requirement that

所有引用(FILE *)对象的函数(名称以_unlocked结尾的函数除外)应表现得好像它们在内部使用flockfile()funlockfile()获取这些(FILE *)对象的所有权一样.

All functions that reference (FILE *) objects, except those with names ending in _unlocked, shall behave as if they use flockfile() and funlockfile() internally to obtain ownership of these (FILE *) objects.

如果在两个线程中都以追加模式打开文件,则每次写入都将安全地放在文件末尾,但是您仍然需要担心在缓冲区填充之前刷新数据.

If you open the file in append mode in both threads, then the writes would be safely at the end of the file each time, but you still have to worry about flushing the data before the buffer fills.

顺便说一句,如果您以附加模式打开文件(O_APPENDopen()"a"fopen()),则所有写操作都应在文件末尾,并且您不应进入交错写入的麻烦-除非,也许,您的独立线程一次使用文件流并且一次写入的内容超过了缓冲区已满,或者除非它们在写入输出的每一行之后都使用了fflush(),或者它们正在使用或其众多亲戚之一,每次都写一行.即使使用追加模式,也有可能遇到问题的方法,但是通常您必须尝试解决这些问题.

Incidentally, if you open the file in append mode (O_APPEND with open(), using "a" with fopen()), then all writes should be at the end of the file, and you should not get into trouble with interleaved writes — unless, perhaps, your independent threads are using file streams and writing more than a buffer-full at a time, or they are using fflush() after writing parts of each line of output, or they are using write() or one of its myriad relatives to write parts of a line each time. There are ways to run into problems even with append mode, but you typically have to be trying to run into them.

这篇关于fopen()是Linux中的线程安全函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆