php - 为什么php线程在我的本地主机上是连续的而不是并行的?

标签 php multithreading pthreads

我想在pthread中使用php并行执行一些任务。我已经在pthreadxampp上安装了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/

相关文章:

javascript - 在 Drupal 7 中输入时将每个单词的第一个字母大写

phpmyadmin 将选定的数据从 SQL 导出到 excel

php - 连接两个表并添加具有相同列id的数据

c++ - C++/Linux 中的线程排序

c - 在 C 中类型转换 pthread 的返回值时出现意外结果

php - 在 Laravel 5 中设置队列

c++ - 在分离线程中执行 - 终止进程(c++ std 11)

java - 如何使用Java防止oracle数据库中的重复插入?

java - 同步线程池ExecutorService

c - 如何使用 C 线程从头到尾读取文件?