Skip to content

Commit

Permalink
Optimize the stop operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
walkor committed Jan 29, 2025
1 parent 6dc10b3 commit c08a211
Showing 1 changed file with 30 additions and 12 deletions.
42 changes: 30 additions & 12 deletions src/Worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -2046,18 +2046,33 @@ public static function stopAll(int $code = 0, mixed $log = ''): void
}
// Execute exit.
$workers = array_reverse(static::$workers);
array_walk($workers, static fn (Worker $worker) => $worker->stop());
array_walk($workers, static fn (Worker $worker) => $worker->stop(false));

if (!static::getGracefulStop() || ConnectionInterface::$statistics['connection_count'] <= 0) {
static::$globalEvent?->stop();
try {
// Ignore Swoole ExitException: Swoole exit.
exit($code);
/** @phpstan-ignore-next-line */
} catch (Throwable) {
// do nothing
$callback = function () use ($code, $workers) {
$allWorkerConnectionClosed = true;
if (!static::getGracefulStop()) {
foreach ($workers as $worker) {
foreach ($worker->connections as $connection) {
// Delay closing, waiting for data to be sent.
if (!$connection->getRecvBufferQueueSize() && !isset($connection->context->closeTimer)) {
$connection->context->closeTimer = Timer::delay(0.01, static fn () => $connection->close());
}
$allWorkerConnectionClosed = false;
}
}
}
}
if ((!static::getGracefulStop() && $allWorkerConnectionClosed) || ConnectionInterface::$statistics['connection_count'] <= 0) {
static::$globalEvent?->stop();
try {
// Ignore Swoole ExitException: Swoole exit.
exit($code);
/** @phpstan-ignore-next-line */
} catch (Throwable) {
// do nothing
}
}
};
Timer::repeat(0.01, $callback);
}
}

Expand Down Expand Up @@ -2566,9 +2581,10 @@ public function run(): void
/**
* Stop current worker instance.
*
* @param bool $force
* @return void
*/
public function stop(): void
public function stop(bool $force = true): void
{
if ($this->stopping === true) {
return;
Expand All @@ -2586,7 +2602,9 @@ public function stop(): void
// Close all connections for the worker.
if (!static::getGracefulStop()) {
foreach ($this->connections as $connection) {
$connection->close();
if ($force || !$connection->getRecvBufferQueueSize()) {
$connection->close();
}
}
}
// Clear callback.
Expand Down

0 comments on commit c08a211

Please sign in to comment.