1
0
mirror of https://github.com/danog/parallel.git synced 2025-01-22 05:51:14 +01:00
parallel/test/Sync/PosixSemaphoreTest.php

94 lines
2.2 KiB
PHP
Raw Normal View History

2016-08-21 23:40:48 -05:00
<?php declare(strict_types = 1);
2016-08-18 17:36:58 -05:00
namespace Amp\Concurrent\Test\Sync;
2016-08-18 11:04:48 -05:00
use Amp\Concurrent\Forking\Fork;
use Amp\Concurrent\Sync\{PosixSemaphore, Semaphore};
/**
* @group posix
* @requires extension sysvmsg
*/
2016-08-18 17:36:58 -05:00
class PosixSemaphoreTest extends AbstractSemaphoreTest {
/**
* @param $locks
*
* @return \Amp\Concurrent\Sync\PosixSemaphore
*/
public function createSemaphore(int $locks) {
2015-09-03 23:23:12 -05:00
return new PosixSemaphore($locks);
}
2016-08-18 17:36:58 -05:00
public function tearDown() {
if ($this->semaphore && !$this->semaphore->isFreed()) {
2015-09-03 23:23:12 -05:00
$this->semaphore->free();
}
}
2016-08-18 17:36:58 -05:00
public function testCloneIsNewSemaphore() {
\Amp\execute(function () {
$this->semaphore = $this->createSemaphore(1);
$clone = clone $this->semaphore;
2016-08-18 17:36:58 -05:00
$lock = yield $clone->acquire();
$this->assertCount(1, $this->semaphore);
$this->assertCount(0, $clone);
$lock->release();
$clone->free();
2016-08-18 17:36:58 -05:00
});
}
2016-08-18 17:36:58 -05:00
public function testFree() {
2015-09-03 23:23:12 -05:00
$this->semaphore = $this->createSemaphore(1);
2015-09-03 23:23:12 -05:00
$this->assertFalse($this->semaphore->isFreed());
2015-09-03 23:23:12 -05:00
$this->semaphore->free();
$this->assertTrue($this->semaphore->isFreed());
}
2015-09-03 23:23:12 -05:00
/**
* @requires extension pcntl
*/
2016-08-18 17:36:58 -05:00
public function testAcquireInMultipleForks() {
\Amp\execute(function () {
2015-09-03 23:23:12 -05:00
$this->semaphore = $this->createSemaphore(1);
2015-12-04 23:50:32 -06:00
$fork1 = new Fork(function (Semaphore $semaphore) {
2016-08-18 17:36:58 -05:00
$lock = yield $semaphore->acquire();
2016-08-21 23:40:48 -05:00
usleep(100000);
2015-08-10 22:35:59 -05:00
2015-09-03 23:23:12 -05:00
$lock->release();
2016-08-18 17:36:58 -05:00
return 0;
2015-09-03 23:23:12 -05:00
}, $this->semaphore);
2015-12-04 23:50:32 -06:00
$fork2 = new Fork(function (Semaphore $semaphore) {
2016-08-18 17:36:58 -05:00
$lock = yield $semaphore->acquire();
2016-08-21 23:40:48 -05:00
usleep(100000);
2015-09-03 23:23:12 -05:00
$lock->release();
2016-08-18 17:36:58 -05:00
return 1;
2015-09-03 23:23:12 -05:00
}, $this->semaphore);
2015-09-03 23:23:12 -05:00
$start = microtime(true);
2015-09-03 23:23:12 -05:00
$fork1->start();
$fork2->start();
2016-08-18 17:36:58 -05:00
yield $fork1->join();
yield $fork2->join();
2016-08-18 17:36:58 -05:00
$this->assertGreaterThan(0.1, microtime(true) - $start);
});
}
}