Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is reading and writing to the same file thread-safe?

I have one file named "data.txt".

I have two threads.

The first thread, read the entire content of the file:

while(1){
    char buf[1000];
    FILE* fp = fopen("data.txt","r");
    while(fread(buf,1,1000,fp)>0){
        /* process data */
    }
    fclose(fp);
}

The second thread append data to the file:

while(1){
    FILE* fp = fopen("data.txt","a");
    fwrite("hello\n",1,6,fp);
    fclose(fp);
}

Is reading and writing in this case (WHITOUT any MUTEX or FILELOCKING) are Thread Safe ? (no segmentation fault, etc...)

like image 990
user3412796 Avatar asked Mar 13 '14 00:03

user3412796


1 Answers

First of all, most standard library functions, among them all but the explicitly unlocked I/O functions, are officially thread safe. See http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_09.html. http://pubs.opengroup.org/onlinepubs/009695299/functions/flockfile.html states explicitly that flockfile() is not needed except for special demands.

A remark about the unlocked functions, which are not thread safe, is interesting:

These functions may safely be used in a multi-threaded program if and only if they are called while the invoking thread owns the ( FILE *) object, as is the case after a successful call to the flockfile() or ftrylockfile() functions.

This implies that the thread safety guarantee of the normal, locked functions is stronger than what you are doing: They are safe even when using the same FILE pointer (the result of one fopen()). It's easy to see how concurrent updating of the bookkeeping information in a FILE struct could corrupt it; the normal standard library functions guarantee not to.

On the other hand the C standard says: "Whether the same file can be simultaneously open multiple times is also implementation-defined." There is CERT advisory to avoid that. This is your use case of more than one FILE struct, obtained by two fopen() calls, potentially without an intervening fclose(), to the same underlying physical file.

That the standard makes this implementation defined may reflect (potential) limitations of certain operating systems.

A remark on the side: Trying a concurrent algorithm successfully a few times is not a guarantee that it is correct. Concurrency issues are ghastly beasts which raise their heads in a non-predictable fashion.

like image 97
Peter - Reinstate Monica Avatar answered Nov 16 '22 00:11

Peter - Reinstate Monica