2016-12-30 02:16:04 +01:00
|
|
|
<?php
|
2015-08-07 22:32:18 +02:00
|
|
|
|
2016-08-23 23:47:40 +02:00
|
|
|
namespace Amp\Parallel\Test\Threading;
|
2016-08-18 18:04:48 +02:00
|
|
|
|
2016-08-23 23:47:40 +02:00
|
|
|
use Amp\Parallel\Sync\Semaphore as SyncSemaphore;
|
|
|
|
use Amp\Parallel\Threading\{Semaphore, Thread};
|
|
|
|
use Amp\Parallel\Test\Sync\AbstractSemaphoreTest;
|
2017-01-09 18:11:25 +01:00
|
|
|
use AsyncInterop\Loop;
|
2015-08-07 22:32:18 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @group threading
|
2015-08-28 22:09:07 +02:00
|
|
|
* @requires extension pthreads
|
2015-08-07 22:32:18 +02:00
|
|
|
*/
|
2016-08-19 00:36:58 +02:00
|
|
|
class SemaphoreTest extends AbstractSemaphoreTest {
|
|
|
|
public function createSemaphore(int $locks) {
|
2015-09-04 06:23:12 +02:00
|
|
|
return new Semaphore($locks);
|
2015-08-07 22:32:18 +02:00
|
|
|
}
|
|
|
|
|
2016-08-19 00:36:58 +02:00
|
|
|
public function testAcquireInMultipleThreads() {
|
2016-12-30 02:17:26 +01:00
|
|
|
Loop::execute(\Amp\wrap(function () {
|
2015-09-04 06:23:12 +02:00
|
|
|
$this->semaphore = $this->createSemaphore(1);
|
2015-09-04 01:10:19 +02:00
|
|
|
|
2015-12-05 06:50:32 +01:00
|
|
|
$thread1 = new Thread(function (SyncSemaphore $semaphore) {
|
2016-08-19 00:36:58 +02:00
|
|
|
$lock = yield $semaphore->acquire();
|
2015-09-04 01:10:19 +02:00
|
|
|
|
2016-08-23 01:25:19 +02:00
|
|
|
usleep(100000);
|
2015-09-04 01:10:19 +02:00
|
|
|
|
|
|
|
$lock->release();
|
|
|
|
|
2016-01-23 07:00:56 +01:00
|
|
|
return 0;
|
2015-09-04 06:23:12 +02:00
|
|
|
}, $this->semaphore);
|
2015-09-04 01:10:19 +02:00
|
|
|
|
2015-12-05 06:50:32 +01:00
|
|
|
$thread2 = new Thread(function (SyncSemaphore $semaphore) {
|
2016-08-19 00:36:58 +02:00
|
|
|
$lock = yield $semaphore->acquire();
|
2015-09-04 01:10:19 +02:00
|
|
|
|
2016-08-23 01:25:19 +02:00
|
|
|
usleep(100000);
|
2015-09-04 01:10:19 +02:00
|
|
|
|
|
|
|
$lock->release();
|
|
|
|
|
2016-01-23 07:00:56 +01:00
|
|
|
return 1;
|
2015-09-04 06:23:12 +02:00
|
|
|
}, $this->semaphore);
|
2015-09-04 01:10:19 +02:00
|
|
|
|
|
|
|
$start = microtime(true);
|
|
|
|
|
|
|
|
$thread1->start();
|
|
|
|
$thread2->start();
|
|
|
|
|
2016-08-19 00:36:58 +02:00
|
|
|
yield $thread1->join();
|
|
|
|
yield $thread2->join();
|
2015-09-04 01:10:19 +02:00
|
|
|
|
2016-08-19 00:36:58 +02:00
|
|
|
$this->assertGreaterThan(0.1, microtime(true) - $start);
|
2016-12-30 02:17:26 +01:00
|
|
|
}));
|
2015-09-04 01:10:19 +02:00
|
|
|
}
|
2015-08-07 22:32:18 +02:00
|
|
|
}
|