2

I'm using the Amp\Loop and want to know that what is the correct way of calling class method with arguments in $worker->enqueue(new CallableTask()).
Here is an example:

<?php
require_once "vendor/autoload.php";
use Amp\Loop;
use Amp\Parallel\Worker\CallableTask;
use Amp\Parallel\Worker\DefaultWorkerFactory;


class Test_Amp {

  public function __construct() {
    $this->run_test();
  }
  public function run_test() {
    Amp\Loop::run(function () {
    $a = "";
    $b = "";
    $factory = new DefaultWorkerFactory();
    $worker = $factory->create();
    $result = yield $worker->enqueue(new CallableTask(array(&$this, 'run_task'), [$a, $b])); // Is it the correct way of calling run_task() ?
    $code = yield $worker->shutdown();
    });
  }

  public function run_task($a, $b) {
    //do something with $a and $b
  }
}

new Test_Amp();

1 Answers1

1

Yes, that's mostly correct. You don't need the & in front of $this.

Instead of using CallableTask, you could also implement your own Task.

Please be aware that your entire object is serialized while being sent to the worker and deserialized in the worker, so modifications to the object made in the child won't be visible in the parent and the other way around.

kelunik
  • 6,750
  • 2
  • 41
  • 70
  • how would one go about doing this? could you please elaborate a bit? – Mr.Flocker May 23 '21 at 02:25
  • @Mr.Flocker You can have a look at the implementation of CallableTask. You need to implement an interface and its run method: https://github.com/amphp/parallel/blob/107e093006376f95a1a95a72e211ef3eced4c400/lib/Worker/CallableTask.php – kelunik May 24 '21 at 17:31