1
0
mirror of https://github.com/danog/parallel.git synced 2024-11-27 12:54:55 +01:00
parallel/tests/Sync/PosixSemaphoreTest.php

100 lines
2.2 KiB
PHP
Raw Normal View History

<?php
namespace Icicle\Tests\Concurrent\Sync;
2015-09-04 06:23:12 +02:00
use Icicle\Concurrent\Forking\Fork;
use Icicle\Concurrent\Sync\PosixSemaphore;
2015-12-05 06:50:32 +01:00
use Icicle\Concurrent\Sync\Semaphore;
use Icicle\Coroutine;
use Icicle\Loop;
/**
* @group posix
* @requires extension sysvmsg
*/
2015-09-04 06:23:12 +02:00
class PosixSemaphoreTest extends AbstractSemaphoreTest
{
2015-09-04 06:23:12 +02:00
public function createSemaphore($locks)
{
2015-09-04 06:23:12 +02:00
return new PosixSemaphore($locks);
}
2015-09-04 06:23:12 +02:00
public function tearDown()
{
if ($this->semaphore && !$this->semaphore->isFreed()) {
2015-09-04 06:23:12 +02:00
$this->semaphore->free();
}
}
public function testCloneIsNewSemaphore()
{
Coroutine\create(function () {
$this->semaphore = $this->createSemaphore(1);
$clone = clone $this->semaphore;
$lock = (yield $clone->acquire());
$this->assertCount(1, $this->semaphore);
$this->assertCount(0, $clone);
$lock->release();
$clone->free();
})->done();
Loop\run();
}
2015-09-04 06:23:12 +02:00
public function testFree()
{
2015-09-04 06:23:12 +02:00
$this->semaphore = $this->createSemaphore(1);
2015-09-04 06:23:12 +02:00
$this->assertFalse($this->semaphore->isFreed());
2015-09-04 06:23:12 +02:00
$this->semaphore->free();
$this->assertTrue($this->semaphore->isFreed());
}
2015-09-04 06:23:12 +02:00
/**
* @requires extension pcntl
*/
public function testAcquireInMultipleForks()
{
Coroutine\create(function () {
2015-09-04 06:23:12 +02:00
$this->semaphore = $this->createSemaphore(1);
2015-12-05 06:50:32 +01:00
$fork1 = new Fork(function (Semaphore $semaphore) {
2015-09-04 06:23:12 +02:00
$lock = (yield $semaphore->acquire());
2015-09-04 06:23:12 +02:00
usleep(1e5);
2015-08-11 05:35:59 +02:00
2015-09-04 06:23:12 +02:00
$lock->release();
2015-09-04 06:23:12 +02:00
yield 0;
}, $this->semaphore);
2015-12-05 06:50:32 +01:00
$fork2 = new Fork(function (Semaphore $semaphore) {
2015-09-04 06:23:12 +02:00
$lock = (yield $semaphore->acquire());
2015-09-04 06:23:12 +02:00
usleep(1e5);
2015-09-04 06:23:12 +02:00
$lock->release();
2015-09-04 06:23:12 +02:00
yield 1;
}, $this->semaphore);
2015-09-04 06:23:12 +02:00
$start = microtime(true);
2015-09-04 06:23:12 +02:00
$fork1->start();
$fork2->start();
2015-09-04 06:23:12 +02:00
yield $fork1->join();
yield $fork2->join();
2015-09-04 06:23:12 +02:00
$this->assertGreaterThan(1, microtime(true) - $start);
});
Loop\run();
}
}