我尝试在Symfony2命令中启动一个简单的线程(使用pthreads ext v3 for php 7创建)。但我想知道我是否因为非序列化闭包而得到错误(我不在任何地方使用闭包)。
命令:
<?php
public function execute(InputInterface $input, OutputInterface $output)
{
$job = new JobThread();
$output->writeln('Starting thread...');
$job->start();
$output->writeln('Waiting for thread to finish executing...');
$job->join();
$output->writeln('Thread finished');
}
JobThread类
<?php
class JobThread extends Thread
{
public function run()
{
echo 'Run' . PHP_EOL;
sleep(3);
echo 'End' . PHP_EOL;
}
}
如果我执行命令,我会得到以下输出:
Starting thread...
PHP Fatal error: Uncaught Exception: Serialization of 'Closure' is not allowed in [no active file]:0
Stack trace:
#0 {main}
thrown in [no active file] on line 0
如果我在命令上下文之外启动线程......
$job = new ThreadJob();
echo 'Starting thread...' . PHP_EOL;
$job->start();
echo 'Waiting for thread to finish executing...' . PHP_EOL;
$job->join();
echo 'Thread finished' . PHP_EOL;
我得到了预期的输出:
Starting thread...
Waiting for thread to finish executing...
Run
End
Thread finished
失败点在哪里?
答案 0 :(得分:2)
我不知道为什么会这样,但以下可能会有一些暗示:
这有效:
$job->start(PTHREADS_INHERIT_ALL ^ PTHREADS_INHERIT_CLASSES);
这不起作用(与没有额外值的调用start完全相同):
$job->start(PTHREADS_INHERIT_ALL);