2016-12-29 19:16:04 -06:00
|
|
|
<?php
|
2015-08-09 22:30:11 -05:00
|
|
|
|
2016-08-23 16:47:40 -05:00
|
|
|
namespace Amp\Parallel\Threading\Internal;
|
2016-08-18 11:04:48 -05:00
|
|
|
|
2016-08-23 16:47:40 -05:00
|
|
|
use Amp\{ Coroutine, Pause };
|
|
|
|
use Amp\Parallel\Sync\Lock;
|
2017-01-09 11:11:25 -06:00
|
|
|
use AsyncInterop\Promise;
|
2015-08-09 22:30:11 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @internal
|
|
|
|
*/
|
2016-08-18 11:04:48 -05:00
|
|
|
class Mutex extends \Threaded {
|
|
|
|
const LATENCY_TIMEOUT = 10;
|
2015-08-09 22:30:11 -05:00
|
|
|
|
2016-08-26 10:10:03 -05:00
|
|
|
/** @var bool */
|
2015-08-09 22:30:11 -05:00
|
|
|
private $lock = true;
|
2016-08-18 11:04:48 -05:00
|
|
|
|
|
|
|
/**
|
2017-01-09 11:11:25 -06:00
|
|
|
* @return \AsyncInterop\Promise
|
2016-08-18 11:04:48 -05:00
|
|
|
*/
|
2016-11-14 17:43:44 -06:00
|
|
|
public function acquire(): Promise {
|
2016-08-18 11:04:48 -05:00
|
|
|
return new Coroutine($this->doAcquire());
|
|
|
|
}
|
|
|
|
|
2015-08-09 22:30:11 -05:00
|
|
|
/**
|
|
|
|
* Attempts to acquire the lock and sleeps for a time if the lock could not be acquired.
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
2016-08-18 11:04:48 -05:00
|
|
|
public function doAcquire(): \Generator {
|
2015-08-09 22:30:11 -05:00
|
|
|
$tsl = function () {
|
|
|
|
return ($this->lock ? $this->lock = false : true);
|
|
|
|
};
|
|
|
|
|
2015-09-01 20:58:22 -05:00
|
|
|
while (!$this->lock || $this->synchronized($tsl)) {
|
2016-08-18 11:04:48 -05:00
|
|
|
yield new Pause(self::LATENCY_TIMEOUT);
|
2015-08-09 22:30:11 -05:00
|
|
|
}
|
|
|
|
|
2016-01-23 00:00:56 -06:00
|
|
|
return new Lock(function () {
|
2015-08-09 22:30:11 -05:00
|
|
|
$this->release();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Releases the lock.
|
|
|
|
*/
|
2016-08-18 11:04:48 -05:00
|
|
|
protected function release() {
|
2015-08-09 22:30:11 -05:00
|
|
|
$this->lock = true;
|
|
|
|
}
|
2015-08-28 14:41:27 -05:00
|
|
|
}
|