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.