2015-08-07 22:32:18 +02:00
|
|
|
<?php
|
|
|
|
namespace Icicle\Concurrent\Sync;
|
|
|
|
|
|
|
|
use Icicle\Concurrent\Exception\LockAlreadyReleasedError;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A handle on an acquired lock from a synchronization object.
|
|
|
|
*
|
|
|
|
* This object is not thread-safe; after acquiring a lock from a mutex or
|
|
|
|
* semaphore, the lock should reside in the same thread or process until it is
|
|
|
|
* released.
|
|
|
|
*/
|
|
|
|
class Lock
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @var callable The function to be called on release.
|
|
|
|
*/
|
|
|
|
private $releaser;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var bool Indicates if the lock has been released.
|
|
|
|
*/
|
2015-08-27 19:52:05 +02:00
|
|
|
private $released = false;
|
2015-08-07 22:32:18 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a new lock permit object.
|
|
|
|
*
|
|
|
|
* @param callable<Lock> $releaser A function to be called upon release.
|
|
|
|
*/
|
|
|
|
public function __construct(callable $releaser)
|
|
|
|
{
|
|
|
|
$this->releaser = $releaser;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if the lock has already been released.
|
|
|
|
*
|
|
|
|
* @return bool True if the lock has already been released, otherwise false.
|
|
|
|
*/
|
|
|
|
public function isReleased()
|
|
|
|
{
|
|
|
|
return $this->released;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Releases the lock.
|
|
|
|
*
|
2015-08-31 00:52:00 +02:00
|
|
|
* @throws LockAlreadyReleasedError If the lock was already released.
|
2015-08-07 22:32:18 +02:00
|
|
|
*/
|
|
|
|
public function release()
|
|
|
|
{
|
|
|
|
if ($this->released) {
|
2015-08-10 05:30:11 +02:00
|
|
|
throw new LockAlreadyReleasedError('The lock has already been released!');
|
2015-08-07 22:32:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Invoke the releaser function given to us by the synchronization source
|
|
|
|
// to release the lock.
|
|
|
|
call_user_func($this->releaser, $this);
|
|
|
|
$this->released = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Releases the lock when there are no more references to it.
|
|
|
|
*/
|
|
|
|
public function __destruct()
|
|
|
|
{
|
|
|
|
if (!$this->released) {
|
|
|
|
$this->release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|