Question

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.

Currently, I have this script :

<?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"));

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

But, here's what I got instead :

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?

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

Was it helpful?

Solution

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.

Do this

$pool = new Pool(1, \MyWorker::class);
$pool->submit(new MyWork("A"));
$pool->submit(new MyWork("B"));
$pool->submit(new MyWork("C"));
$pool->shutdown();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top