Semaphores fully implemented

This commit is contained in:
Chris 2018-04-15 20:48:22 +02:00
parent 612cfc2035
commit 4652e464b9
3 changed files with 41 additions and 6 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
/vendor/ /vendor/
/composer.lock /composer.lock
/doc

View File

@ -8,18 +8,25 @@ use NoccyLabs\Ipc\Key\KeyInterface;
class Semaphore class Semaphore
{ {
public function __construct(KeyInterface $key, int $max) protected $resource;
public function __construct(KeyInterface $key, int $max, $perm = 0660, $autorelease = 1)
{ {
$this->resource = sem_get($key->getKey(), $max, $perm, $autorelease);
} }
public function acquire(float $timeout) public function destroy()
{ {
sem_remove($this->resource);
} }
public function release() public function acquire(float $timeout = 0):bool
{ {
return sem_acquire($this->resource, true);
}
public function release():bool
{
return sem_release($this->resource);
} }
} }

View File

@ -0,0 +1,27 @@
<?php
namespace NoccyLabs\Ipc\Sem;
use NoccyLabs\Ipc\Key\FileKey;
class SemaphoreTest extends \PhpUnit\Framework\TestCase
{
public function testCreatingAndAquiringSemaphore()
{
$key = new FileKey(__FILE__);
$sem = new Semaphore($key, 2);
$this->assertTrue($sem->acquire());
$this->assertTrue($sem->acquire());
$this->assertFalse($sem->acquire());
$this->assertTrue($sem->release());
$this->assertTrue($sem->acquire());
$this->assertFalse($sem->acquire());
$this->assertTrue($sem->release());
$this->assertTrue($sem->release());
}
}