2015-08-10 05:30:11 +02:00
|
|
|
<?php
|
2015-08-29 08:40:10 +02:00
|
|
|
namespace Icicle\Concurrent\Threading\Internal;
|
2015-08-10 05:30:11 +02:00
|
|
|
|
2015-08-29 08:40:10 +02:00
|
|
|
use Icicle\Concurrent\Sync\Lock;
|
2015-08-10 05:30:11 +02:00
|
|
|
use Icicle\Coroutine;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @internal
|
|
|
|
*/
|
2015-08-29 08:40:10 +02:00
|
|
|
class Mutex extends \Threaded
|
2015-08-10 05:30:11 +02:00
|
|
|
{
|
|
|
|
const LATENCY_TIMEOUT = 0.01; // 10 ms
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var bool
|
|
|
|
*/
|
|
|
|
private $lock = true;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Attempts to acquire the lock and sleeps for a time if the lock could not be acquired.
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
2016-01-23 07:00:56 +01:00
|
|
|
public function acquire(): \Generator
|
2015-08-10 05:30:11 +02:00
|
|
|
{
|
|
|
|
$tsl = function () {
|
|
|
|
return ($this->lock ? $this->lock = false : true);
|
|
|
|
};
|
|
|
|
|
2015-09-02 03:58:22 +02:00
|
|
|
while (!$this->lock || $this->synchronized($tsl)) {
|
2016-01-23 07:00:56 +01:00
|
|
|
yield from Coroutine\sleep(self::LATENCY_TIMEOUT);
|
2015-08-10 05:30:11 +02:00
|
|
|
}
|
|
|
|
|
2016-01-23 07:00:56 +01:00
|
|
|
return new Lock(function () {
|
2015-08-10 05:30:11 +02:00
|
|
|
$this->release();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Releases the lock.
|
|
|
|
*/
|
|
|
|
protected function release()
|
|
|
|
{
|
|
|
|
$this->lock = true;
|
|
|
|
}
|
2015-08-28 21:41:27 +02:00
|
|
|
}
|