Tuesday, July 2, 2019

c - After calling fclose(), how quickly will the file be available to another thread?



I have an application that runs on Windows and Linux. It creates a file, writes to it, and calls fclose(). After some indeterminate time, the name of the file is sent another thread. The other thread opens the file using fopen() and reads its contents.



One user is reporting the application fails on Debian 6 unless he creates a short delay before opening the file.



When fclose() is called and returns, how quickly will the file be available to other threads through fopen()?


Answer




Your question is a bit ambiguous, so I'll try to answer several interpretations.



If your question is how soon after fclose it's possible to fopen the file again, the answer is simply that it's possible any time, even before fclose. POSIX does not permit file opens to be mutually exclusive; it's possible to open a file as many times as you like as long as you don't hit the system open-file limits. Even if you're on a non-conforming platform like Windows with a pseudo-POSIX-threads implementation, as long as the fopen is ordered after the fclose, you're fine, because the underlying close operation must complete before fclose can return.



If your concern on the other hand is about availability of the data written by one thread for reading by another thread, then as long as you can establish a "happens-before" relationship between the flush (either explicitly via fflush or as part of the fclose operation) that wrote the data and the reads elsewhere, you're fine. Any pthread synchronization functions such a use of a mutex, or pthread_join, would be sufficient to establish this relationship.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...