2022-06-17 11:59:19 +08:00
|
|
|
<?php
|
2023-04-16 01:45:34 +08:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
2022-06-17 11:59:19 +08:00
|
|
|
namespace Kiri;
|
|
|
|
|
|
2026-06-12 23:57:25 +08:00
|
|
|
use Swoole\Coroutine;
|
|
|
|
|
use Swoole\Coroutine\Channel;
|
|
|
|
|
|
2022-06-17 11:59:19 +08:00
|
|
|
class Coordinator
|
|
|
|
|
{
|
|
|
|
|
|
2023-12-12 15:35:38 +08:00
|
|
|
const string WORKER_START = 'worker:start';
|
2022-06-17 11:59:19 +08:00
|
|
|
|
2026-07-03 18:29:45 +08:00
|
|
|
private bool $wait = false;
|
2026-06-12 23:57:25 +08:00
|
|
|
|
|
|
|
|
private ?Channel $channel = null;
|
2022-06-17 11:59:19 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
|
|
|
|
public function yield(): void
|
|
|
|
|
{
|
2026-06-12 23:57:25 +08:00
|
|
|
if (Coroutine::getCid() > 0) {
|
2026-07-03 18:29:45 +08:00
|
|
|
if ($this->channel instanceof Channel) {
|
|
|
|
|
$this->channel->pop();
|
2026-06-12 23:57:25 +08:00
|
|
|
}
|
2026-07-03 18:29:45 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ($this->wait === false) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
while ($this->wait === true) {
|
|
|
|
|
usleep(1000);
|
2026-06-12 23:57:25 +08:00
|
|
|
}
|
2022-06-17 11:59:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
2026-06-12 23:57:25 +08:00
|
|
|
public function wait(): void
|
2022-06-17 11:59:19 +08:00
|
|
|
{
|
2026-07-03 18:29:45 +08:00
|
|
|
Coroutine::getCid() > 0 ? $this->channel = new Channel(1) : $this->wait = true;
|
2022-06-17 11:59:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
|
|
|
|
public function done(): void
|
|
|
|
|
{
|
2026-07-03 18:29:45 +08:00
|
|
|
if (Coroutine::getCid() > 0) {
|
|
|
|
|
$this->channel?->push(true);
|
|
|
|
|
$this->channel->close();
|
|
|
|
|
$this->channel = null;
|
|
|
|
|
} else {
|
|
|
|
|
$this->wait = false;
|
|
|
|
|
}
|
2022-06-17 11:59:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|