I was wondering if there are circumstances where Thread::start()
returns false
. The manual isn't very clear about this.
I was able to let start()
fail in the following cases. In all cases it throws a RuntimeException
, so no false
returned.
Try to start a thread twice
$thread = new Thread;
$thread->start();
$thread->start(); // RuntimeException
Exhaust system resources
class TestThread extends Thread
{
public function run()
{
sleep(PHP_INT_MAX);
}
}
$threads = [];
for (;;) {
$thread = new TestThread;
if (!$thread->start()) { // RuntimeException eventually
echo 'FALSE returned.', PHP_EOL; // never printed
break;
}
$threads[] = $thread;
}
Try to start thread again from thread (Note: You can start threads from threads; this is just an example to let it fail.)
class TestThread extends Thread
{
public function run()
{
// necessary to see the exception
set_exception_handler(function ($exception) {
throw $exception;
});
self::start(); // RuntimeException
}
}
(new TestThread)->start();