1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-11 16:49:51 +01:00
parallel/lib/Sync/Lock.php

64 lines
1.6 KiB
PHP
Raw Normal View History

2016-12-30 02:16:04 +01:00
<?php
2016-08-23 23:47:40 +02:00
namespace Amp\Parallel\Sync;
2016-08-18 18:04:48 +02:00
2016-08-23 23:47:40 +02:00
use Amp\Parallel\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.
*/
2016-08-18 18:04:48 +02:00
class Lock {
2016-08-26 17:10:03 +02:00
/** @var callable The function to be called on release. */
private $releaser;
2016-08-26 17:10:03 +02:00
/** @var bool Indicates if the lock has been released. */
2015-08-27 19:52:05 +02:00
private $released = false;
/**
* Creates a new lock permit object.
*
* @param callable<Lock> $releaser A function to be called upon release.
*/
2016-08-18 18:04:48 +02:00
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.
*/
2016-08-18 18:04:48 +02:00
public function isReleased(): bool {
return $this->released;
}
/**
* Releases the lock.
*
2015-08-31 00:52:00 +02:00
* @throws LockAlreadyReleasedError If the lock was already released.
*/
2016-08-18 18:04:48 +02:00
public function release() {
if ($this->released) {
throw new LockAlreadyReleasedError('The lock has already been released!');
}
// Invoke the releaser function given to us by the synchronization source
// to release the lock.
2016-01-23 07:00:56 +01:00
($this->releaser)($this);
$this->released = true;
}
/**
* Releases the lock when there are no more references to it.
*/
2016-08-18 18:04:48 +02:00
public function __destruct() {
if (!$this->released) {
$this->release();
}
}
}