Do examples exist for returning data from an AMPHP future?

50 views Asked by At

After reading the documentation for AMPHP I haven't been able to track down an example for returning results from a threaded process, however many examples for printing data from a thread exist. Are any published examples available?

Here is the problem I am trying to solve (modified from reference [here]):

use Amp\Future;
use Amp\Sync\LocalMutex;
use Amp\Sync\LocalParcel;
use function Amp\async;
use function Amp\delay;

$thread_main = array();
$thread_main['a'] = 1;
$thread_main['b'] = 2;

$parcel = new LocalParcel(new LocalMutex(), $thread_main);

$future1 = async(function () use ($parcel): void {
    
  echo "<p> Coroutine started \n";
  $value = $parcel->synchronized(function (array $value): array { 
    $value['c'] = $value['a'] + $value['b']; 
    return $value;
  });
  echo "<p> Coroutine result: " . $value['c'] .  "\n";
});

$future1->await();

// I'd like to return the result (ie. 3) here, in the main thread.

echo '<p> the end';

Looked for help in these locations

https://github.com/amphp https://amphp.org/sync

1

There are 1 answers

1
tree317 On

After some further exploration the answer was right there in the code itself.

$result = $parcel->synchronized(function (array $value): array { return $value; });

print_r($result); // all values (a b c)