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

74 lines
1.8 KiB
PHP
Raw Normal View History

2016-12-30 02:16:04 +01:00
<?php
2016-08-23 23:47:40 +02:00
namespace Amp\Parallel\Threading;
2016-08-18 18:04:48 +02:00
2016-08-23 23:47:40 +02:00
use Amp\Parallel\Sync\Semaphore as SyncSemaphore;
2016-11-15 00:43:44 +01:00
use Interop\Async\Promise;
/**
* 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 {
2016-08-26 17:10:03 +02:00
/** @var Internal\Semaphore */
private $semaphore;
2016-08-26 17:10:03 +02:00
/** @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-11-15 00:43:44 +01:00
public function acquire(): Promise {
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
}