-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.php
58 lines (44 loc) · 1.58 KB
/
process.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
use Amp\Delayed;
use PHPinnacle\Ensign\Dispatcher;
use PHPinnacle\Ensign\HandlerRegistry;
require __DIR__ . '/../vendor/autoload.php';
Amp\Loop::run(function () {
$handlers = new HandlerRegistry;
$handlers
->add('spawn', function (callable $process) {
static $pid = 1;
$gen = $process($pid);
yield from $gen;
return $pid++;
})
->add('send', function (int $pid, string $message, ...$arguments) {
$signal = sprintf('%s.%d', $message, $pid);
return yield $signal => $arguments;
})
->add('receive', function (int $pid, string $message, callable $handler) use ($handlers) {
$signal = sprintf('%s.%d', $message, $pid);
$handlers->add($signal, $handler);
})
;
$dispatcher = new Dispatcher($handlers);
$receiver = yield $dispatcher->dispatch('spawn', function (int $pid) {
yield 'receive' => [$pid, 'ping', function () {
echo 'Ping!' . \PHP_EOL;
}];
yield 'receive' => [$pid, 'pong', function () {
echo 'Pong!' . \PHP_EOL;
}];
});
$senderOne = $dispatcher->dispatch('spawn', function () use ($receiver) {
yield 'send' => [$receiver, 'ping'];
yield new Delayed(500);
yield 'send' => [$receiver, 'ping'];
});
$senderTwo = $dispatcher->dispatch('spawn', function () use ($receiver) {
yield 'send' => [$receiver, 'pong'];
yield new Delayed(100);
yield 'send' => [$receiver, 'pong'];
});
yield [$senderOne, $senderTwo];
});