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

72 lines
1.7 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()
{
print "Child sleeping for 5 seconds...\n";
2015-07-12 15:57:04 -05:00
yield $this->sem->acquire();
sleep(4);
yield $this->sem->release();
$this->synchronized(function () {
$this->data = 'progress';
});
2015-07-12 15:57:04 -05:00
//throw new Exception('Testing exception bubbling.');
sleep(2);
}
}
2015-07-12 15:57:04 -05:00
$generator = function () {
$before = memory_get_usage();
$context = new Test();
$after = memory_get_usage();
$context->data = 'blank';
printf("Object memory: %d bytes\n", $after - $before);
$context->start();
2015-07-12 15:57:04 -05:00
Loop\timer(1, function () use ($context) {
$context->sem->acquire()->then(function () use ($context) {
print "Finally got semaphore from child!\n";
return $context->sem->release();
});
});
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()) {
$context->synchronized(function ($context) {
printf("Context data: '%s'\n", $context->data);
});
}
});
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();