PHP 5.3.8的互斥锁

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

Calling flock() twice on the same file handle will return true both times and would not block, because the function checks if the file handle is already locked and if it is, it returns true. This is expected behavior. However it will work as you expect if multiple processes run in parallel, because every process will have a different file handle. If you want to test this in a single process, create multiple handles to the same file object:

$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