parallel icon indicating copy to clipboard operation
parallel copied to clipboard

[question] Calling $this kills the process

Open mercurykd opened this issue 2 years ago • 4 comments

from php:8.2-zts
run pecl install parallel && docker-php-ext-enable parallel
<?php

use parallel\Runtime;

class Test
{
    public function test($arg)
    {
        $this->third();
        echo "$arg\n";
    }

    public function third()
    {
        echo "third\n";
    }

    public function run()
    {
        $r = new Runtime();
        $r->run($this->test(...), ['test']);
    }
}
$t = new Test();

$t->run();

Calling the third method via $this kills the process, why?

mercurykd avatar Mar 04 '23 22:03 mercurykd

You can't use by-reference: https://www.php.net/manual/en/parallel.run.php#refsect1-parallel.run-argv-characteristics

hschimpf avatar Mar 28 '23 21:03 hschimpf

thanks for the answer. can you show how to write the code in this case?

mercurykd avatar Mar 29 '23 06:03 mercurykd

One way you can do is create the instance of your class Test inside the runtime. So all the references to $this are inside the thread (Runtime).

use parallel\Runtime;

class Test
{
    public function test($arg)
    {
        $this->third();
        echo "$arg\n";
    }

    public function third()
    {
        echo "third\n";
    }
}

$r = new Runtime();
$r->run(function(...$args) {

  $t = new Test();
  $t->test(...$args);

}, ['test']);

The above code is just an example, I didn't run it.

hschimpf avatar Mar 29 '23 13:03 hschimpf

Hey @mercurykd, checkout this library that I made. It may simplify the usage of $this in your code.

hschimpf avatar Jul 19 '23 19:07 hschimpf