/** * Closure thread * * @param bool $debug */ function processThreadClosure($debug = false) { $async = Thread::$useForks; if ($debug) { echo '-----------------------', PHP_EOL, "Closure thread test: ", $async ? 'Async' : 'Sync', PHP_EOL, '-----------------------', PHP_EOL; } // ---- $expected = mt_rand(999, 99999); $thread = SimpleThread::create(function () use($expected) { return $expected; }, null, $debug); $result = $thread->run()->wait()->getResult(); $this->assertSame($expected, $result); // ---- $result = $thread->run()->wait()->getResult(); $this->assertSame($expected, $result); $thread->cleanup(); // ---- $expected = mt_rand(999, 99999); $thread = SimpleThread::create(function ($arg) { return $arg; }, null, $debug); $result = $thread->run($expected)->wait()->getResult(); $this->assertSame($expected, $result); // ---- $expected = mt_rand(999, 99999); $result = $thread->run($expected)->wait()->getResult(); $this->assertSame($expected, $result); $thread->cleanup(); }
$jobs[] = $started[$threadId]; echo "error: {$started[$threadId]} ", "(thread {$threadId}): #{$errorCode} - {$errorMessage}", PHP_EOL; unset($started[$threadId]); $left++; } } } while ($num > 0); // After work it's strongly recommended to clean // resources obviously to avoid leaks $pool->cleanup(); // ---------------------------------------------- echo PHP_EOL, 'Simple example with one "closure" thread', PHP_EOL; $num = 10; // Number of tasks $thread = SimpleThread::create(function ($arg) { return $arg; }); // "closure" threads are not preforked by default // and not multitask too. You can change it via // the second argument of `SimpleThread::create`. for ($i = 0; $i < $num; $i++) { $value = $i; // Run task and wait for the result if ($thread->run($value)->wait()->getSuccess()) { // Success $result = $thread->getResult(); echo 'result: ' . $result . PHP_EOL; } else { // Error handling here // processing is not successful if thread dies // when worked or working timeout exceeded