0

When I run the following code, the individual Threads seems to be executed in sequence, one at the time. I was expecting them to run in parallel. Is there something wrong with my code, or shall I start to look at my environment? I am running Apache, PHP 7 on a Windows machine.

<?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/>";
}


?>

The output of the code above always becomes something like this:

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
1
  • The funny thing about threads is that you have little or no control over what sequence they run in once they are forked. It is quite common for threads forked in sequence to be executed in sequence. I'm not familiar with PThreads, so I'm not sure how these threads might be forked -- your code has no calls to pcntl_fork or anything. You might also make sure you fork more threads than your processor can handle at once. If it has 4 hyperthreading cores, it can handle 8 at once. Try forking 16 threads. Commented Dec 2, 2017 at 21:58

1 Answer 1

1

OK, I got it now.

A Worker does not run all stacked threads in parallel, they are executed one at the time.

To run all the jobs at the same time, one must use a Pool.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.