我想在pthread
中使用php
并行执行一些任务。我已经在pthread
的xampp
上安装了win10
,我只是从网站复制了一些示例,但是所有示例的结果都是顺序的,而不是并行的!
http://www.smddzcy.com/2016/01/tutorial-multi-threading-in-php7-pthreads/的一个示例:
<?php
class SomeThreadedClass extends Thread
{
private $tID;
public $data;
public function __construct(int $tID)
{
$this->tID = $tID;
$this->data = $tID . ":" . date('H:i:s');
}
public function run()
{
echo $this->tID . " started.\n";
sleep($this->tID);
echo $this->tID . " ended. " . date('H:i:s') . "\n";
}
}
$threads = [];
for ($i = 1; $i < 5; $i++) {
$threads[$i] = new SomeThreadedClass($i);
$threads[$i]->start(); // start the job on the background
}
for ($i = 1; $i < 5; $i++) {
$threads[$i]->join(); // wait until job is finished,
echo $threads[$i]->data . "\n"; // then we can access the data
}
该网站上的结果是:
1 started.
2 started.
3 started.
4 started.
1 ended. 18:18:52
1:18:18:51
2 ended. 18:18:53
2:18:18:51
3 ended. 18:18:54
3:18:18:51
4 ended. 18:18:55
4:18:18:51
当我在本地主机上运行代码时,得到以下结果:
1 started.
1 ended. 13:11:24
2 started.
2 ended. 13:11:25
3 started. 3 ended. 13:11:26
4 started. 4 ended. 13:11:27
1:15:41:23
2:15:41:23
3:15:41:23
4:15:41:23
为什么线程在我的本地主机上是顺序的而不是并行的?
最佳答案
线程正在并行执行。您可以通过查看输出时间来判断。所有线程在同一时间启动,并且每个线程在每个连接线程之间仅完成1秒。假设在产生的每个新线程上sleep
时间都在增加,则如果它们依次执行,则每个线程完成之间的时间间隔将增加。
例如,将产生的线程和脚本的部分连接更改为以下内容(强制顺序执行):
for ($i = 1; $i < 5; $i++) {
$threads[$i] = new SomeThreadedClass($i);
$threads[$i]->start(); // start the job on the background
$threads[$i]->join(); // wait until job is finished,
echo $threads[$i]->data . "\n"; // then we can access the data
}
将输出类似于以下内容:
1 started.
1 ended. 15:14:06
1:15:14:05
2 started.
2 ended. 15:14:08
2:15:14:06
3 started.
3 ended. 15:14:11
3:15:14:08
4 started.
4 ended. 15:14:15
4:15:14:11
请注意不同的开始时间以及完成时间之间的增量间隔。
至于为什么要按顺序接收输出,这只是输出缓冲区如何处理多个线程的输出。我的输出是不同的,但是随后我使用的是OSX。
关于php - 为什么php线程在我的本地主机上是连续的而不是并行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870295/