获取文件的独占读/写锁定以进行原子更新 [英] Obtain exclusive read/write lock on a file for atomic updates

查看:105
本文介绍了获取文件的独占读/写锁定以进行原子更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个用作计数器的PHP文件.它将(a)回显txt文件的当前值,并b)使用排他锁递增该文件,以便在使用该文件时没有其他脚本可以读取或写入该文件.

I want to have a PHP file that is used as a counter. It will a) echo the current value of a txt file, and b) increment that file using an exclusive lock so no other scripts can read or write to it while it's being used.

用户A将写入并递增此数字,而用户B请求读取文件.用户A是否可以锁定此文件,以便在用户A的写操作完成之前没有人可以读取或写入该文件?

User A will write and increment this number, while User B requests to read the file. Is it possible that User A can lock this file so no one can read or write to it until User A's write is finished?

我过去曾经使用过flock,但是我不确定如何让文件等待直到可用,而不是退出,如果它已经被锁定

I've used flock in the past, but I'm not sure how to get the file to wait until it is available, rather than quitting if it's already been locked

我的目标是:

LOCK counter.txt; write to counter.txt;

同时

Read counter.txt; realize it's locked so wait until that lock is finished.

//

$fp = fopen("counter.txt", 'w+');
if(flock($fp, LOCK_EX)) {
    fwrite($fp, $counter + 1);
    flock($fp, LOCK_UN);
} else {
    // try again??
}

fclose($fp);

推荐答案

摘自文档:由默认情况下,此功能将一直阻塞,直到获得请求的锁为止

因此,只需在读取器(LOCK_SH)和写入器(LOCK_EX)中使用flock,它就会起作用. 但是,我强烈不建议使用不超时的阻塞群,因为这意味着如果出现问题,则您的程序将永远挂起.为了避免这种情况,请使用非阻塞请求(同样,它在doc中):

So simply use flock in your reader (LOCK_SH) and writer (LOCK_EX), and it is going to work. However I highly discourage use of blocking flock without timeout as this means that if something goes wrong then your program is going to hang forever. To avoid this use non-blocking request like this (again, it is in doc):

/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
    echo 'Unable to obtain lock';
}

将其包装在for循环中,并在失败的n-ttry(或总等待时间)后进入睡眠并中断.

And wrap it in a for loop, with sleep and break after failed n-tries (or total wait time).

您还可以查找用法的一些示例 ninja-mutex 库的一部分.

You can also look for some examples of usage here. This class is a part of ninja-mutex library in which you may be interested too.

这篇关于获取文件的独占读/写锁定以进行原子更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆