2017-12-13 06:38:23 +01:00
|
|
|
#!/usr/bin/env php
|
|
|
|
<?php
|
2018-10-07 16:50:45 +02:00
|
|
|
require \dirname(__DIR__).'/vendor/autoload.php';
|
2017-12-13 06:38:23 +01:00
|
|
|
|
2018-10-21 17:34:08 +02:00
|
|
|
use Amp\ByteStream;
|
2017-12-13 06:38:23 +01:00
|
|
|
use Amp\Delayed;
|
|
|
|
use Amp\Loop;
|
|
|
|
use Amp\Parallel\Context\Process;
|
|
|
|
use Amp\Parallel\Sync\SharedMemoryParcel;
|
|
|
|
|
|
|
|
Loop::run(function () {
|
|
|
|
// Create a parcel that then can be accessed in any number of child processes.
|
2018-10-07 16:50:45 +02:00
|
|
|
$parcel = SharedMemoryParcel::create($id = \bin2hex(\random_bytes(10)), 1);
|
2017-12-13 06:38:23 +01:00
|
|
|
|
2018-10-21 17:34:08 +02:00
|
|
|
$context = yield Process::run([
|
2017-12-13 06:38:23 +01:00
|
|
|
__DIR__ . "/parcel-process.php",
|
|
|
|
$id, // Send parcel ID to child process as command argument.
|
|
|
|
]);
|
|
|
|
|
2018-10-21 17:34:08 +02:00
|
|
|
\assert($context instanceof Process);
|
|
|
|
|
|
|
|
// Pipe any data written to the STDOUT in the child process to STDOUT of this process.
|
2018-10-25 05:31:47 +02:00
|
|
|
Amp\Promise\rethrow(ByteStream\pipe($context->getStdout(), ByteStream\getStdout()));
|
2018-10-21 17:34:08 +02:00
|
|
|
|
2017-12-13 06:38:23 +01:00
|
|
|
yield new Delayed(100); // Give the process time to start and access the parcel.
|
|
|
|
|
|
|
|
yield $parcel->synchronized(function (int $value) {
|
|
|
|
return $value + 1;
|
|
|
|
});
|
|
|
|
|
|
|
|
yield $context->join(); // Wait for child process to finish.
|
|
|
|
|
2018-10-07 16:50:45 +02:00
|
|
|
\printf("Final value of parcel: %d\n", yield $parcel->unwrap());
|
2017-12-13 06:38:23 +01:00
|
|
|
});
|