0

The man pages ( https://linux.die.net/man/2/flock ) are not clear regarding whether a LOCK_UN operation on flock() is allowed if unlock has already been called in another thread. In my case, multiple threads could be reading the same file via multiple file descriptors, each of which would call flock(fd, LOCK_SH) and then flock(fd, LOCK_UN) after reading. Would this produce undefined behavior?

For example:

//Two duplicate threads do:
FILE* fp = fopen("path", "r");
if (fp) {
    int fd = fileno(fp); // there is much more complexity in-between that makes fopen easier to use
    flock(fd, LOCK_SH);
    my_read_function(fp); // does something with a global (not the case in actual code)
    fclose(fp); // apparently the file might already be unlocked here if only this thread has opened it, but assume that I may use C++ to create some safer wrapper to handle exceptions and decide to use explicit flock calls outside the destructor
    flock(fd, LOCK_UN);
}

Also I am not convinced that flock is necessary at all given that threads only read. Is it good practice to use flock() in this way nontheless?

Thank you in advance.

synchronizer
  • 1,955
  • 1
  • 14
  • 37
  • 1
  • If it is guaranteed that all threads *only* read the file, no locking is necessary. – alk May 01 '17 at 09:06
  • 1
    Related (for writing): http://stackoverflow.com/q/9462532/694576 – alk May 01 '17 at 09:13
  • I think the idea was that someone in another process might accidentally try writing to a file somewhere else in the program, in which case locking would be safer. Based on the above it sounds as though flock()ing is useless for threads in the same process. Is this correct? Also, I am still wondering about the unlocking multiple times behavior. – synchronizer May 01 '17 at 13:56

0 Answers0