1
0
mirror of https://github.com/danog/parallel.git synced 2025-01-22 22:11:11 +01:00
parallel/examples/fork.php

65 lines
1.4 KiB
PHP
Raw Normal View History

<?php
require dirname(__DIR__).'/vendor/autoload.php';
use Icicle\Concurrent\Forking\ForkContext;
2015-07-12 15:57:04 -05:00
use Icicle\Coroutine\Coroutine;
use Icicle\Loop;
class Test extends ForkContext
{
2015-07-12 15:57:04 -05:00
/**
* @synchronized
*/
public $data;
public function run()
{
2015-07-13 12:30:00 -05:00
print "Child sleeping for 4 seconds...\n";
2015-07-12 15:57:04 -05:00
sleep(4);
2015-07-13 12:30:00 -05:00
yield $this->synchronized(function () {
$this->data = 'progress';
});
2015-07-13 12:30:00 -05:00
print "Child sleeping for 2 seconds...\n";
sleep(2);
}
}
2015-07-12 15:57:04 -05:00
$generator = function () {
$context = new Test();
$context->data = 'blank';
$context->start();
2015-07-12 15:57:04 -05:00
Loop\timer(1, function () use ($context) {
2015-07-13 12:30:00 -05:00
$context->synchronized(function ($context) {
print "Finally got lock from child!\n";
2015-07-12 15:57:04 -05:00
});
});
2015-07-12 15:57:04 -05:00
$timer = Loop\periodic(1, function () use ($context) {
static $i;
$i = $i + 1 ?: 1;
print "Demonstrating how alive the parent is for the {$i}th time.\n";
if ($context->isRunning()) {
2015-07-15 18:10:27 -05:00
$context->synchronized(function ($context) {
printf("Context data: '%s'\n", $context->data);
});
2015-07-12 15:57:04 -05:00
}
});
2015-07-12 15:57:04 -05:00
try {
yield $context->join();
print "Context done!\n";
} catch (Exception $e) {
print "Error from child!\n";
print $e."\n";
} finally {
$timer->stop();
}
};
2015-07-10 16:17:43 -05:00
2015-07-12 15:57:04 -05:00
new Coroutine($generator());
Loop\run();