From bc4cfa6ede591707a78ea443b8a8371505518def Mon Sep 17 00:00:00 2001 From: Aaron Piotrowski Date: Sat, 7 Dec 2024 10:03:49 -0600 Subject: [PATCH 1/2] Register shutdown function to clear event loop --- examples/shutdown.php | 36 ++++++++++++++++++++++++++++++++++++ src/EventLoop.php | 29 +++++++++++++++++++++++++++-- 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 examples/shutdown.php diff --git a/examples/shutdown.php b/examples/shutdown.php new file mode 100644 index 0000000..1fb79a9 --- /dev/null +++ b/examples/shutdown.php @@ -0,0 +1,36 @@ +isRunning()) { - throw new \Error("Can't swap the event loop driver while the driver is running"); + if (isset(self::$driver)) { + if (self::$driver->isRunning()) { + throw new \Error("Can't swap the event loop driver while the driver is running"); + } + } else { + \register_shutdown_function(self::onShutdown(...), 0); } try { @@ -67,6 +71,27 @@ protected function now(): float } } + private static function onShutdown(int $invocationCount): void + { + $driver = self::getDriver(); + + $pending = false; + foreach ($driver->getIdentifiers() as $identifier) { + if ($driver->isEnabled($identifier) && $driver->isReferenced($identifier)) { + $pending = true; + break; + } + } + + if ($pending) { + $driver->run(); + } + + if (!$invocationCount++ || $pending) { + \register_shutdown_function(self::onShutdown(...), $invocationCount); + } + } + /** * Queue a microtask. * From 1f1e9be8463b7f029b2ec1e2ee1d82853cb80302 Mon Sep 17 00:00:00 2001 From: Aaron Piotrowski Date: Sat, 7 Dec 2024 10:12:00 -0600 Subject: [PATCH 2/2] Collect GC cycles first --- src/EventLoop.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/EventLoop.php b/src/EventLoop.php index 2c764e7..655c5de 100644 --- a/src/EventLoop.php +++ b/src/EventLoop.php @@ -73,6 +73,8 @@ protected function now(): float private static function onShutdown(int $invocationCount): void { + \gc_collect_cycles(); + $driver = self::getDriver(); $pending = false;