多个要求如何避免种族危险?

时间:2015-08-17 17:52:07

标签: php parallel-processing race-condition

为了保护脚本形式的竞争危险,我正在考虑代码示例所描述的方法

$file = 'yxz.lockctrl';
// if file exists, it means that some other request is running
while (file_exists($file))
{
    sleep(1);
}

file_put_contents($file, '');

// do some work

unlink($file);

如果我这样做,是否可以同时从多个请求创建同名文件?

我知道有php互斥量。我想在没有任何扩展的情况下处理这种情况(如果可能的话)。

该计划的任务是处理拍卖申请中的出价。我想按顺序处理每个出价请求。尽可能延迟。

1 个答案:

答案 0 :(得分:0)

据我了解,您希望确保一次只运行一个特定的代码。互斥锁或类似机制可用于此目的。我本人使用锁文件来提供一种可在许多平台上使用并且不依赖于仅在Linux等上可用的特定库的解决方案。

为此,我编写了一个小型Lock类。请注意,它使用了我的库中的一些非标准函数,例如,获取临时文件的存储位置等。但是您可以轻松地对其进行更改。

<?php   
    class Lock
    {
        private $_owned             = false;

        private $_name              = null;
        private $_lockFile          = null;
        private $_lockFilePointer   = null;

        public function __construct($name)
        {
            $this->_name = $name;
            $this->_lockFile = PluginManager::getInstance()->getCorePlugin()->getTempDir('locks') . $name . '-' . sha1($name . PluginManager::getInstance()->getCorePlugin()->getPreference('EncryptionKey')->getValue()).'.lock';
        }

        public function __destruct()
        {
            $this->release();
        }

        /**
         * Acquires a lock
         *
         * Returns true on success and false on failure.
         * Could be told to wait (block) and if so for a max amount of seconds or return false right away.
         *
         * @param bool $wait
         * @param null $maxWaitTime
         * @return bool
         * @throws \Exception
         */
        public function acquire($wait = false, $maxWaitTime = null) {
            $this->_lockFilePointer = fopen($this->_lockFile, 'c');
            if(!$this->_lockFilePointer) {
                throw new \RuntimeException(__('Unable to create lock file', 'dliCore'));
            }

            if($wait && $maxWaitTime === null) {
                $flags = LOCK_EX;
            }
            else {
                $flags = LOCK_EX | LOCK_NB;
            }

            $startTime = time();

            while(1) {
                if (flock($this->_lockFilePointer, $flags)) {
                    $this->_owned = true;
                    return true;
                } else {
                    if($maxWaitTime === null || time() - $startTime > $maxWaitTime) {
                        fclose($this->_lockFilePointer);
                        return false;
                    }
                    sleep(1);
                }
            }
        }

        /**
         * Releases the lock
         */
        public function release()
        {
            if($this->_owned) {
                @flock($this->_lockFilePointer, LOCK_UN);
                @fclose($this->_lockFilePointer);
                @unlink($this->_lockFile);
                $this->_owned = false;
            }
        }
    }

用法

现在您可以有两个同时运行并执行相同脚本的进程

过程1

$lock = new Lock('runExpensiveFunction');

if($lock->acquire()) {
  // Some expensive function that should only run one at a time
  runExpensiveFunction();
  $lock->release();
}

过程2

$lock = new Lock('runExpensiveFunction');

// Check will be false since the lock will already be held by someone else so the function is skipped
if($lock->acquire()) {
  // Some expensive function that should only run one at a time
  runExpensiveFunction();
  $lock->release();
}

另一种选择是让第二个进程等待第一个进程完成,而不是跳过代码。

$lock = new Lock('runExpensiveFunction');

// Process will now wait for the lock to become available. A max wait time can be set if needed.
if($lock->acquire(true)) {
  // Some expensive function that should only run one at a time
  runExpensiveFunction();
  $lock->release();
}

Ram磁盘 要限制使用锁定文件对HDD / SSD的写入次数,您可以创建一个RAM磁盘以将其存储在其中。

在Linux上,您可以将以下内容添加到/etc/fstab

tmpfs       /mnt/ramdisk tmpfs   nodev,nosuid,noexec,nodiratime,size=1024M   0 0

在Windows上,您可以下载类似ImDisk Toolkit的文件并使用它创建一个虚拟磁盘。

ImDisk RamDisk Configuration Tool