PHP flock()非阻塞仍然阻塞为什么? [英] PHP flock() non-blocking still block why?

查看:238
本文介绍了PHP flock()非阻塞仍然阻塞为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flock()函数通过获取临时文件上的锁来检查脚本的另一个实例是否已在运行,因此下一个实例应检查该文件是否未锁定,否则它将停止

I'm using flock() function to check if another instance of the script is already running by obtaining the lock on a temporary file so next instance should check if the file is not locked otherwise it stops

<?php    
$fp = fopen("/var/tmp/your.lock", "w");
if (!flock($fp, LOCK_EX|LOCK_NB)) { // try to get exclusive lock, non-blocking
    die("Another instance is running");
} 

//my script 
sleep(10);
echo 'completed successfully';

当从不同的浏览器同时调用两次文件时,脚本可以正常工作,它可以等待我是否从同一浏览器同时打开了两个实例,即,第一个调用获得了锁定,第二个调用了锁定而不是关闭

the script works without problem when calling the file twice at the same time from different browsers while it waits if I opened two instances at the same time from the same browser i.e the first call get the lock and the second wait for the lock and not closing

我知道可能还有其他方法可以检查实例实例是否已在工作,但大多数方法会先执行某操作然后撤消该操作,并且在我的用例中,脚本可能会在任何时间结束,因为它可能需要很长时间甚至超过内存限制或出于任何原因

I know there may be other ways to check if a file an instance is already working but most of them will do a thing then undo it and in my use case the script may end any time as it may take long time or exceed memory limit or by any reason

有什么帮助吗?

推荐答案

问题是:

在浏览器中使用相同的URL两次调用相同的脚本将通过相同的进程进行线程化,并且flock()函数在进程层无阻塞地工作,从而导致第二个脚本等待

calling the same script twice with the same url from the browser will thread via the same process and flock() function non-blocking working on the process layer causing the second script to wait

作为示例调用 example.com/test.php 两次将导致两个请求在同一个进程上工作,同时附加任何随机变量将为每个单独的请求(例如

as example calling example.com/test.php twice will cause the two requests work on the same process wile appending any random variable will create separate process for each single request like

example.com/test.php?rand=1
example.com/test.php?rand=2

效果很好.

这篇关于PHP flock()非阻塞仍然阻塞为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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