gpt4 book ai didi

php - 与 PHP 5.3.8 互斥

转载 作者:行者123 更新时间:2023-12-04 00:46:40 24 4
gpt4 key购买 nike

我在运行 Windows XP SP3 和 Apache 2.2.21 的 Web 服务器上使用 PHP 5.3.8,我需要在其中创建互斥量。经过一些研究,我遇到了 flock命令并像这样实现它:

class Mutex
{
private $lock_ = null;

// create a mutex with with a given id. This ID must be system unique.
// [string] id - a unique id
// return - true on success
public function Initialize($id)
{
$this->lock_ = fopen($id, 'a');
return is_resource($this->lock_);
}

// destroy the mutex
public function Destroy()
{
$result = false;
if (is_resource($this->lock_));
{
$result = flock($this->lock_, LOCK_UN);
$result &= fclose($this->lock_);
$this->lock_ = null;
}
return $result;
}

// exclusively lock the resource
// return - true on success
public function Lock()
{
if (is_resource($this->lock_))
return flock($this->lock_, LOCK_EX);
return false;
}

// release the locked resource
// return - true on success
public function Release()
{
if (is_resource($this->lock_))
return flock($this->lock_, LOCK_UN);
return false;
}
}

但是,当我去使用这个类时:

$this->cache_lock_ = new Mutex();
$this->cache_lock_->Initialize("e:\\cache_lock");

if ($this->cache_lock_->Lock())
echo "Acquired 1 ".PHP_EOL;
if ($this->cache_lock_->Lock())
echo "Acquired 2 ".PHP_EOL;
$this->cache_lock_->Release();

$this->cache_lock_->Destroy();

我看到打印的 Acquired 1 Acquired 2 表明锁被获取了两次,尽管我指定它是独占的。

任何人都可以建议我做错了什么吗?理想情况下,我希望在资源可用之前阻止第二次 Lock() 调用。

谢谢,保罗H

最佳答案

在同一个文件句柄上调用 flock() 两次将返回 true 并且不会阻塞,因为该函数检查文件句柄是否已经被锁定,如果是,它返回 true。这是预期的行为。但是,如果多个进程并行运行,它将按预期工作,因为每个进程都有不同的文件句柄。如果您想在单个进程中对此进行测试,请为同一文件对象创建多个句柄:

$a = new Mutex();
$a->Initialize("file.lock");
$a->Lock(); // this will simply lock the file object
$b = new Mutex();
$b->Initialize("file.lock");
$b->Lock(); // this will block, because the file is locked by $a

关于php - 与 PHP 5.3.8 互斥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8744873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com