<?php
use Swow\Channel;
use Swow\Coroutine;
use Swow\Selector;
$c1 = new Channel(1);
Coroutine::run(function () use ($c1) {
sleep(2);
$c1->push('result 1');
});
$s = new Selector();
$channel = $s->pop($c1)->pop(select_timeout(1))->commit();
if ($channel === $c1) {
echo $s->fetch(), PHP_EOL;
} else {
echo 'timeout 1', PHP_EOL;
}
$c2 = new Channel(1);
Coroutine::run(function () use ($c2) {
sleep(2);
$c2->push('result 2');
});
$s = new Selector();
$channel = $s->pop($c2)->pop(select_timeout(3))->commit();
if ($channel === $c2) {
echo $s->fetch(), PHP_EOL;
} else {
echo 'timeout 2', PHP_EOL;
}
function select_timeout(int $time): Channel
{
$chan = new Channel();
Coroutine::run(function () use ($chan, $time) {
sleep($time);
$chan->push(true);
});
return $chan;
}
<?php
use Swow\Channel;
use Swow\Selector;
$messages = new Channel();
$signals = new Channel();
$s = new Selector();
$channel = $s->pop($messages)->pop(select_default())->commit();
if ($channel === $messages) {
echo 'received message: ' . $s->fetch(), PHP_EOL;
} else {
echo 'no message received', PHP_EOL;
}
$s = new Selector();
$channel = $s->push($messages, 'hi')->pop(select_default())->commit();
if ($channel === $messages) {
echo 'sent message: ' . $messages->pop(), PHP_EOL;
} else {
echo 'no message sent', PHP_EOL;
}
$s = new Selector();
$channel = $s->pop($messages)->pop($signals)->pop(select_default())->commit();
if ($channel === $messages) {
echo 'received message: ' . $s->fetch(), PHP_EOL;
} elseif ($channel === $signals) {
echo 'received signal: ' . $s->fetch(), PHP_EOL;
} else {
echo 'no activity', PHP_EOL;
}
function select_default(): Channel
{
$chan = new Channel(1);
$chan->push(true);
return $chan;
}
<?php
use Swow\Channel;
use Swow\ChannelException;
use Swow\Coroutine;
$jobs = new Channel(5);
$done = new Channel();
Coroutine::run(function () use ($jobs, $done) {
while(true) {
try {
$j = $jobs->pop();
echo 'received job: ', $j, PHP_EOL;
} catch (ChannelException) {
echo 'received all jobs', PHP_EOL;
$done->push(true);
return;
}
}
});
for ($j = 1; $j <= 3; $j++) {
echo 'sent job: ', $j, PHP_EOL;
$jobs->push($j);
}
echo 'sent all jobs', PHP_EOL;
$jobs->close();
$done->pop();