带pthread的PHP中的Worker和Pool [英] Worker and Pool in PHP with pthreads

查看:50
本文介绍了带pthread的PHP中的Worker和Pool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习PHP中的多线程.我已经知道多线程的基本知识,例如创建线程并一起运行多个线程,但是我仍然对Worker和Pool感到困惑.

I'm currently learning multithreading in PHP. I already know the basic of multithreading like creating threads and running multiple of them together, but I'm still confused about Worker and Pool.

当前,我有这个脚本:

<?php

class MyWork extends Threaded {

    public $name;

    public function __construct($name) {
        echo "Constructing worker $name\n";
        $this->name = $name;
    }

    public function run() {
        echo "Worker $this->name start running\n";
        for ($i = 1; $i <= 5; $i++) {
            echo "Worker $this->name : $i\n";
            sleep(1);
        }
    }

}

class MyWorker extends Worker {
    public function run() {}
}

$pool = new Pool(1, \MyWorker::class);
$pool->submit(new MyWork("A"));
$pool->submit(new MyWork("B"));
$pool->submit(new MyWork("C"));

以我的理解,这应该创建一个最多只能同时运行1个工人的工人池,对吗?因此,我期望这种输出:

With my understanding, this should create a pool of workers with a maximum number of 1 worker running at one time right? Hence, I Expect this kind of output :

Constructing worker A
Constructing worker B
Constructing worker C
Worker A start running
Worker A : 1
Worker A : 2
Worker A : 3
Worker A : 4
Worker A : 5
Worker B start running
Worker B : 1
Worker B : 2
Worker B : 3
Worker B : 4
Worker B : 5
Worker C start running
Worker C : 1
Worker C : 2
Worker C : 3
Worker C : 4
Worker C : 5

但是,这是我得到的:

Constructing worker A
Constructing worker B
Worker A start running
Constructing worker C
Worker A : 1
Worker  : 2
Worker  : 3
Worker  : 4
Worker  : 5
Worker  start running
Worker  : 1
Worker  : 2
Worker  : 3
Worker  : 4
Worker  : 5
Worker  start running
Worker  : 1
Worker  : 2
Worker  : 3
Worker  : 4
Worker  : 5

为什么工人的名字只出现一次然后又消失了?

Why the worker's name only appeared once and then disappear like that?

注意:我在Windows 8.1上将PHP 5.5.10与phtreads 2.0.4结合使用,并且通过CLI运行脚本.

Note : I'm using PHP 5.5.10 with phtreads 2.0.4 on Windows 8.1, and I run the script via CLI.

推荐答案

在脚本末尾(在最后一个commit()之后),工作线程被销毁,并且池在仍在执行对象的同时进入关闭状态,这就解释了为什么名字消失了.

At the end of the script (after the last submit()), the workers are being destroyed and the pool goes into shutdown while it is still executing objects, which explains why name disappears.

执行此操作

$pool = new Pool(1, \MyWorker::class);
$pool->submit(new MyWork("A"));
$pool->submit(new MyWork("B"));
$pool->submit(new MyWork("C"));
$pool->shutdown();

这篇关于带pthread的PHP中的Worker和Pool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆