【问题标题】:Does flock() only apply to the current method?flock() 是否仅适用于当前方法?
【发布时间】:2016-09-02 14:29:04
【问题描述】:

flock() 函数是否仅在与执行代码相同的方法中使用时才有效?

比如下面的代码,加锁成功:

public function run()
{
    $filePointerResource = fopen('/tmp/lock.txt', 'w');
    if (flock($filePointerResource, LOCK_EX)) {
        sleep(10);
    } else {
        exit('Could not get lock!');
    }
}

但是,在下面的代码中,锁是不成功的:

public function run()
{
    if ($this->lockFile()) {
        sleep(10);
    } else {
        exit('Could not get lock!');
    }
}

private function lockFile()
{
    $filePointerResource = fopen('/tmp/lock.txt', 'w');
    return flock($filePointerResource, LOCK_EX);
}

我没有看到任何关于此的文档,所以我对这种行为感到困惑。我使用的是 php 版本 5.5.35。

【问题讨论】:

    标签: php methods file-locking flock


    【解决方案1】:

    我认为基于类的尝试的问题在于,当 lockFile 方法完成时,$filePointerResource 超出范围,这可能就是释放锁的原因

    这在支持该理论的情况下起作用

    <?php
    
    class test {
        public function run()
        {
            $fp = fopen('lock.txt', 'w');
            if ($this->lockFile($fp)) {
                echo 'got a lock'.PHP_EOL;
                sleep(5);
            } 
            /*
             * Not going to do anything as the attempt to lock EX will
             * block until a lock can be gained 
    
            else {
                exit('Could not get lock!'.PHP_EOL);
            }
            */
        }
    
        private function lockFile($fp)
        {
            return flock($fp, LOCK_EX);
        }
    }
    
    $t = new test();
    $t->run();
    

    因此,如果您想在多次调用类方法时锁定文件,最好将文件句柄保留为类属性,那么只要类被实例化并在范围内,它就会保持在范围内。

    <?php
    
    class test {
        private $fp;
    
        public function run()
        {
            $this->fp = fopen('lock.txt', 'w');
            if ($this->lockFile()) {
                echo 'got a lock'.PHP_EOL;
                sleep(5);
            } 
            /*
             * Not going to do anything as the attempt to lock EX will
             * block until a lock can be gained 
    
            else {
                exit('Could not get lock!'.PHP_EOL);
            }
            */
        }
    
        private function lockFile()
        {
            return flock($this->fp, LOCK_EX);
        }
    }
    
    $t = new test();
    $t->run();
    

    【讨论】:

    • 哇,这就解释了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多