1
0
mirror of https://github.com/danog/parallel.git synced 2024-11-27 12:54:55 +01:00
parallel/examples/fork.php

40 lines
960 B
PHP
Raw Normal View History

2015-08-07 01:59:25 +02:00
#!/usr/bin/env php
<?php
require dirname(__DIR__).'/vendor/autoload.php';
2015-08-24 18:20:22 +02:00
use Icicle\Concurrent\Forking\Fork;
2015-08-03 22:10:20 +02:00
use Icicle\Coroutine;
2015-07-12 22:57:04 +02:00
use Icicle\Loop;
2015-08-03 22:10:20 +02:00
Coroutine\create(function () {
2015-08-24 18:20:22 +02:00
$context = Fork::spawn(function () {
2015-07-13 19:30:00 +02:00
print "Child sleeping for 4 seconds...\n";
2015-07-12 22:57:04 +02:00
sleep(4);
yield $this->send('Data sent from child.');
2015-07-13 19:30:00 +02:00
print "Child sleeping for 2 seconds...\n";
sleep(2);
2015-08-07 01:59:25 +02:00
yield 42;
2015-07-12 22:57:04 +02:00
});
2015-07-12 22:57:04 +02:00
$timer = Loop\periodic(1, function () use ($context) {
static $i;
$i = $i ? ++$i : 1;
2015-07-12 22:57:04 +02:00
print "Demonstrating how alive the parent is for the {$i}th time.\n";
});
2015-07-12 22:57:04 +02:00
try {
printf("Received the following from child: %s\n", (yield $context->receive()));
2015-08-07 01:59:25 +02:00
printf("Child ended with value %d!\n", (yield $context->join()));
2015-07-12 22:57:04 +02:00
} catch (Exception $e) {
print "Error from child!\n";
print $e."\n";
2015-07-12 22:57:04 +02:00
} finally {
$timer->stop();
}
2015-08-03 22:10:20 +02:00
});
2015-07-10 23:17:43 +02:00
Loop\run();