Trait
LockTrait
Implements LockInterface: a lock that is reentrant for the coroutine holding it and fair for the others.
Introduction#
Use it in a class that needs to protect state across waits. The coroutines asking while the lock is held are served in the order they asked: the holder hands the lock to the first in line.
Class synopsis#
trait LockTrait {
/* Methods */
public LockTrait::lock(Closure $callable, ?float $timeout = null): mixed
}Methods#
| Method | Description |
|---|---|
lock | Runs $callable while holding the lock of this object, and returns what it returns. |
Examples#
class Account
{
use phasync\Util\LockTrait;
private int $balance = 100;
public function withdraw(int $amount): void
{
$this->lock(function () use ($amount) {
$balance = $this->balance;
phasync::sleep(0.01); // another coroutine would interleave here, without the lock
$this->balance = $balance - $amount;
});
}
}See also#
LockInterfaceAn object that runs a closure while holding a lock that other coroutines wait for.SynchronizedA mutex for coroutines, identified by a string or an object: only one coroutine at a time runs a closure for the same token.