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

47 lines
900 B
PHP
Raw Normal View History

<?php
namespace Icicle\Concurrent\Threading\Internal;
use Icicle\Concurrent\Sync\Lock;
use Icicle\Coroutine;
/**
* @internal
*/
class Mutex extends \Threaded
{
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
{
$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);
}
2016-01-23 07:00:56 +01:00
return new Lock(function () {
$this->release();
});
}
/**
* Releases the lock.
*/
protected function release()
{
$this->lock = true;
}
2015-08-28 21:41:27 +02:00
}