1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-11 00:29:46 +01:00
parallel/lib/Threading/Semaphore.php

78 lines
1.9 KiB
PHP
Raw Normal View History

2016-08-22 06:40:48 +02:00
<?php declare(strict_types = 1);
2016-08-18 18:04:48 +02:00
namespace Amp\Concurrent\Threading;
use Amp\Concurrent\Sync\Semaphore as SyncSemaphore;
2016-08-19 00:36:58 +02:00
use Interop\Async\Awaitable;
/**
* An asynchronous semaphore based on pthreads' synchronization methods.
*
* This is an implementation of a thread-safe semaphore that has non-blocking
* acquire methods. There is a small tradeoff for asynchronous semaphores; you
* may not acquire a lock immediately when one is available and there may be a
* small delay. However, the small delay will not block the thread.
*/
2016-08-18 18:04:48 +02:00
class Semaphore implements SyncSemaphore {
/**
2015-08-31 00:52:00 +02:00
* @var Internal\Semaphore
*/
private $semaphore;
/**
* @var int
*/
private $maxLocks;
/**
2015-08-31 00:52:00 +02:00
* Creates a new semaphore with a given number of locks.
*
2015-08-31 20:49:26 +02:00
* @param int $locks The maximum number of locks that can be acquired from the semaphore.
*/
2016-08-19 00:36:58 +02:00
public function __construct(int $locks) {
$this->init($locks);
}
/**
* Initializes the semaphore with a given number of locks.
*
* @param int $locks
*/
2016-08-19 00:36:58 +02:00
private function init(int $locks) {
if ($locks < 1) {
2016-08-23 01:25:19 +02:00
throw new \Error("The number of locks should be a positive integer");
}
$this->semaphore = new Internal\Semaphore($locks);
$this->maxLocks = $locks;
}
/**
* {@inheritdoc}
*/
2016-08-19 00:36:58 +02:00
public function count(): int {
return $this->semaphore->count();
}
/**
* {@inheritdoc}
*/
2016-08-19 00:36:58 +02:00
public function getSize(): int {
return $this->maxLocks;
}
/**
* {@inheritdoc}
*/
2016-08-19 00:36:58 +02:00
public function acquire(): Awaitable {
return $this->semaphore->acquire();
}
/**
* Clones the semaphore, creating a new instance with the same number of locks, all available.
*/
2016-08-19 00:36:58 +02:00
public function __clone() {
$this->init($this->getSize());
}
2015-08-31 00:52:00 +02:00
}