2020-07-21 22:12:34 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
require 'vendor/autoload.php';
|
|
|
|
|
|
|
|
use Amp\Loop;
|
|
|
|
use danog\Loop\SignalLoop;
|
|
|
|
|
|
|
|
use function Amp\delay;
|
|
|
|
|
|
|
|
class SigLoop extends SignalLoop
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Loop name.
|
|
|
|
*
|
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
private $name;
|
|
|
|
/**
|
|
|
|
* Constructor.
|
|
|
|
*
|
|
|
|
* @param string $name Loop name
|
|
|
|
*/
|
2020-07-22 18:18:57 +02:00
|
|
|
public function __construct(string $name)
|
2020-07-21 22:12:34 +02:00
|
|
|
{
|
|
|
|
$this->name = $name;
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Main loop.
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
|
|
|
public function loop(): \Generator
|
|
|
|
{
|
|
|
|
$number = 0;
|
2020-07-22 18:18:57 +02:00
|
|
|
while (true) {
|
|
|
|
if (yield $this->waitSignal(delay(1000))) {
|
|
|
|
echo "Got exit signal in $this!".PHP_EOL;
|
|
|
|
return;
|
|
|
|
}
|
2020-07-21 22:12:34 +02:00
|
|
|
echo "$this: $number".PHP_EOL;
|
2020-07-22 18:18:57 +02:00
|
|
|
$number++;
|
2020-07-21 22:12:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Get loop name.
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
public function __toString(): string
|
|
|
|
{
|
|
|
|
return $this->name;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Loop::run(function () {
|
|
|
|
/** @var SigLoop[] */
|
|
|
|
$loops = [];
|
|
|
|
for ($x = 0; $x < 10; $x++) {
|
2020-07-22 18:18:57 +02:00
|
|
|
$loop = new SigLoop("Loop number $x");
|
2020-07-21 22:12:34 +02:00
|
|
|
$loop->start();
|
|
|
|
yield delay(100);
|
|
|
|
$loops []= $loop;
|
|
|
|
}
|
|
|
|
yield delay(5000);
|
2020-07-22 18:18:57 +02:00
|
|
|
echo "Closing all loops!".PHP_EOL;
|
2020-07-21 22:12:34 +02:00
|
|
|
foreach ($loops as $loop) {
|
2020-07-22 18:18:57 +02:00
|
|
|
$loop->signal(true);
|
2020-07-21 22:12:34 +02:00
|
|
|
}
|
|
|
|
});
|