1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-12 17:17:20 +01:00
parallel/lib/Threading/Internal/Mutex.php

51 lines
1.1 KiB
PHP
Raw Normal View History

2016-08-22 06:40:48 +02:00
<?php declare(strict_types = 1);
2016-08-23 23:47:40 +02:00
namespace Amp\Parallel\Threading\Internal;
2016-08-18 18:04:48 +02:00
2016-08-23 23:47:40 +02:00
use Amp\{ Coroutine, Pause };
use Amp\Parallel\Sync\Lock;
2016-08-18 18:04:48 +02:00
use Interop\Async\Awaitable;
/**
* @internal
*/
2016-08-18 18:04:48 +02:00
class Mutex extends \Threaded {
const LATENCY_TIMEOUT = 10;
2016-08-26 17:10:03 +02:00
/** @var bool */
private $lock = true;
2016-08-18 18:04:48 +02:00
/**
* @return \Interop\Async\Awaitable
*/
public function acquire(): Awaitable {
return new Coroutine($this->doAcquire());
}
/**
* Attempts to acquire the lock and sleeps for a time if the lock could not be acquired.
*
* @return \Generator
*/
2016-08-18 18:04:48 +02:00
public function doAcquire(): \Generator {
$tsl = function () {
return ($this->lock ? $this->lock = false : true);
};
2015-09-02 03:58:22 +02:00
while (!$this->lock || $this->synchronized($tsl)) {
2016-08-18 18:04:48 +02:00
yield new Pause(self::LATENCY_TIMEOUT);
}
2016-01-23 07:00:56 +01:00
return new Lock(function () {
$this->release();
});
}
/**
* Releases the lock.
*/
2016-08-18 18:04:48 +02:00
protected function release() {
$this->lock = true;
}
2015-08-28 21:41:27 +02:00
}