当我运行以下代码时,各个线程似乎按顺序执行,一次执行。我期待他们并行运行。我的代码有问题,还是我应该开始关注我的环境?我在Windows机器上运行Apache,PHP 7。
<?php
class Searcher extends Worker
{
public $data = [];
public function addData($data)
{
$this->data[] = $data;
}
}
class MyThread extends Threaded
{
public function __construct($param)
{
$this->param = $param;
}
public function run()
{
sleep(3);
$this->worker->addData(
$this->param." - TIME: ".microtime(true)
);
}
}
$worker = new Searcher();
$params = ['thread1', 'thread2', 'thread3', 'thread4', 'thread5', 'thread6', 'thread7'];
foreach ($params as &$param) {
$worker->stack(new MyThread($param));
}
$worker->start();
$worker->join();
foreach ($worker->data as $data) {
echo $data."<br/>";
}
?>
上面代码的输出总是这样:
thread1 - TIME: 1512249412.3757
thread2 - TIME: 1512249415.7776
thread3 - TIME: 1512249419.1792
thread4 - TIME: 1512249422.5813
thread5 - TIME: 1512249425.9825
thread6 - TIME: 1512249429.384
thread7 - TIME: 1512249432.7859
答案 0 :(得分:1)
好的,我现在知道了。
Worker不会并行运行所有堆叠的线程,它们会在当时执行一次。
要同时运行所有作业,必须使用Pool。