2015-08-07 22:32:18 +02:00
|
|
|
<?php
|
2015-08-29 08:40:10 +02:00
|
|
|
namespace Icicle\Concurrent\Threading;
|
|
|
|
|
|
|
|
use Icicle\Concurrent\Sync\SemaphoreInterface;
|
2015-08-07 22:32:18 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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.
|
|
|
|
*/
|
2015-08-29 08:40:10 +02:00
|
|
|
class Semaphore implements SemaphoreInterface
|
2015-08-07 22:32:18 +02:00
|
|
|
{
|
|
|
|
/**
|
2015-08-31 00:52:00 +02:00
|
|
|
* @var Internal\Semaphore
|
2015-08-07 22:32:18 +02:00
|
|
|
*/
|
2015-08-10 05:30:11 +02:00
|
|
|
private $semaphore;
|
2015-08-07 22:32:18 +02:00
|
|
|
|
|
|
|
/**
|
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.
|
2015-08-07 22:32:18 +02:00
|
|
|
*/
|
2015-08-31 20:49:26 +02:00
|
|
|
public function __construct($locks)
|
2015-08-07 22:32:18 +02:00
|
|
|
{
|
2015-08-31 00:52:00 +02:00
|
|
|
$this->semaphore = new Internal\Semaphore($locks);
|
2015-08-07 22:32:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the number of currently available locks.
|
|
|
|
*
|
|
|
|
* @return int The number of available locks.
|
|
|
|
*/
|
|
|
|
public function count()
|
|
|
|
{
|
2015-08-10 05:30:11 +02:00
|
|
|
return $this->semaphore->count();
|
2015-08-07 22:32:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function acquire()
|
|
|
|
{
|
2015-08-10 05:30:11 +02:00
|
|
|
return $this->semaphore->acquire();
|
2015-08-07 22:32:18 +02:00
|
|
|
}
|
2015-08-31 00:52:00 +02:00
|
|
|
}
|