2015-08-07 01:59:25 +02:00
|
|
|
#!/usr/bin/env php
|
2015-07-14 00:30:59 +02:00
|
|
|
<?php
|
2015-08-03 22:09:26 +02:00
|
|
|
require dirname(__DIR__).'/vendor/autoload.php';
|
2015-07-14 00:30:59 +02:00
|
|
|
|
2015-08-22 23:27:44 +02:00
|
|
|
use Icicle\Concurrent\Threading\Thread;
|
2015-08-03 22:09:26 +02:00
|
|
|
use Icicle\Coroutine;
|
2015-07-14 00:30:59 +02:00
|
|
|
use Icicle\Loop;
|
|
|
|
|
2015-08-07 01:59:25 +02:00
|
|
|
$timer = Loop\periodic(1, function () {
|
2015-08-07 22:30:14 +02:00
|
|
|
static $i;
|
|
|
|
$i = $i ? ++$i : 1;
|
|
|
|
print "Demonstrating how alive the parent is for the {$i}th time.\n";
|
2015-08-07 01:59:25 +02:00
|
|
|
});
|
|
|
|
|
2015-08-03 22:09:26 +02:00
|
|
|
Coroutine\create(function () {
|
|
|
|
// Create a new child thread that does some blocking stuff.
|
2015-08-24 20:46:17 +02:00
|
|
|
$context = Thread::spawn(function () {
|
2015-08-18 17:12:06 +02:00
|
|
|
printf("\$this: %s\n", get_class($this));
|
|
|
|
|
|
|
|
printf("Received the following from parent: %s\n", (yield $this->receive()));
|
|
|
|
|
2015-08-25 16:53:17 +02:00
|
|
|
yield $this->synchronized(function () {
|
|
|
|
print "Sleeping for 3 seconds...\n";
|
|
|
|
sleep(3);
|
2015-08-18 17:12:06 +02:00
|
|
|
|
2015-08-25 16:53:17 +02:00
|
|
|
yield $this->send('Data sent from child.');
|
2015-08-07 22:30:14 +02:00
|
|
|
|
2015-08-25 16:53:17 +02:00
|
|
|
print "Sleeping for 2 seconds...\n";
|
|
|
|
sleep(2);
|
|
|
|
});
|
2015-08-07 22:30:14 +02:00
|
|
|
|
|
|
|
yield 42;
|
2015-08-03 22:09:26 +02:00
|
|
|
});
|
2015-07-27 00:53:00 +02:00
|
|
|
|
2015-08-18 17:12:06 +02:00
|
|
|
yield $context->send('Start data');
|
|
|
|
|
2015-08-25 16:53:17 +02:00
|
|
|
yield $context->synchronized(function () {
|
|
|
|
printf("Cooperatively sleeping in parent for 2 seconds before releasing lock...\n");
|
2015-08-18 17:12:06 +02:00
|
|
|
|
2015-08-25 16:53:17 +02:00
|
|
|
yield Coroutine\sleep(2);
|
|
|
|
});
|
2015-08-18 17:12:06 +02:00
|
|
|
|
2015-08-07 22:30:14 +02:00
|
|
|
printf("Received the following from child: %s\n", (yield $context->receive()));
|
|
|
|
printf("Thread ended with value %d!\n", (yield $context->join()));
|
2015-08-18 17:12:06 +02:00
|
|
|
})->cleanup([$timer, 'stop'])->done();
|
2015-07-14 00:30:59 +02:00
|
|
|
|
|
|
|
Loop\run();
|