当锁已经解锁时,flock(fd,LOCK_UN)是否未定义?

时间:2017-05-01 04:27:55

标签: c multithreading undefined-behavior locks flock

如果在另一个线程中已经调用了unlock,则手册页(https://linux.die.net/man/2/flock)不清楚是否允许对flock()执行LOCK_UN操作。在我的例子中,多个线程可以通过多个文件描述符读取相同的文件,每个文件描述符在调用后调用flock(fd,LOCK_SH)然后flock(fd,LOCK_UN)。这会产生不明确的行为吗?

例如:

//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);
}

此外,由于线程只读取,我不相信羊群是必要的。以这种方式使用flock()是不错的做法?

提前谢谢。

0 个答案:

没有答案