0
當我運行下面的代碼時,單個線程似乎按順序執行,一次執行。我期待他們能夠平行運行。我的代碼有什麼問題,或者我應該開始看看我的環境?我在Windows機器上運行Apache,PHP 7。PHP Pthreads - 線程不併行運行
<?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
關於線程的有趣之處在於,一旦它們被分叉,你幾乎無法控制它們運行的順序。順序分叉的線程順序執行是很常見的。我對PThreads不熟悉,所以我不確定這些線程可能如何分叉 - 你的代碼沒有對[pcntl_fork](http://php.net/pcntl_fork)或其他任何東西的調用。你也可以確保你的fork多於你的處理器一次處理的線程數。如果它有4個超線程核心,它可以一次處理8個。嘗試分叉16個線程。 –