/** * Pool, events * * @param bool $debug * @param bool $bigData * * @throws Exception */ function processPoolEvent($debug = false, $bigData = false) { $events = 3; $num = 12; $threads = 3; $async = Thread::$useForks; if ($debug) { echo '-----------------------', PHP_EOL, "Thread pool events test: ", $async ? 'Async' : 'Sync', PHP_EOL, '-----------------------', PHP_EOL; } $pool = new ThreadPool(__NAMESPACE__ . '\\TestThreadEvents', $threads, null, null, $debug); $arg = mt_rand(12, 987); if ($bigData) { $arg = str_repeat($arg, 100000); } $jobs = $worked = array(); $test = $this; $cb = function ($event, $threadId, $e_data, $e_arg) use($arg, $test, &$jobs) { /** @var $test TestCase */ $test->assertSame($arg, $e_arg); $test->assertSame(TestThreadEvents::EV_PROCESS, $event); if (!isset($jobs[$threadId])) { $jobs[$threadId] = 0; } $test->assertEquals($jobs[$threadId]++, $e_data); }; $pool->bind(TestThreadEvents::EV_PROCESS, $cb, $arg); $i = 0; $left = $num; $maxI = ceil($num * 1.5); do { while ($left > 0 && $pool->hasWaiting()) { $threadId = $pool->run($events); $this->assertNotEmpty($threadId); $worked[$threadId] = true; $left--; } $results = $pool->wait($failed); $this->assertEmpty($failed, 'Failed results: ' . print_r($failed, true)); if ($results) { foreach ($results as $threadId => $res) { $num--; $this->assertTrue(isset($jobs[$threadId]), "Thread #{$threadId}"); $this->assertSame($events, $jobs[$threadId]); unset($jobs[$threadId]); } } $i++; } while ($num > 0 && $i < $maxI); $this->assertSame(0, $num, 'All jobs must be done'); $pool->cleanup(); }