I am using PHP 5.3.8 on a web server running Windows XP SP3 and Apache 2.2.21 where I need to create a mutex. After some research, I've come across the flock command and implemented it like this:
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;
}
}
But, when I go to use this class:
$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();
I see Acquired 1 Acquired 2
printed indicating the lock was acquired twice despite my specifying that it be exclusive.
Can anybody suggest what I'm doing wrong? Ideally, I would like the second Lock() call toblock until the resource is available.
Thanks, PaulH