From 49f577b9a04e5169e95332f9a0f87865fa7c393e Mon Sep 17 00:00:00 2001 From: vdergachyov Date: Sun, 1 Jan 2023 18:07:21 +0600 Subject: [PATCH] Reduce CPU usage in the connection thread loop --- aiosqlite/core.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/aiosqlite/core.py b/aiosqlite/core.py index 4acc895..273b8aa 100644 --- a/aiosqlite/core.py +++ b/aiosqlite/core.py @@ -69,6 +69,10 @@ def __init__( DeprecationWarning, ) + def _stop_running(self): + self._running = False + self._tx.put_nowait(None) + @property def _conn(self) -> sqlite3.Connection: if self._connection is None: @@ -99,12 +103,13 @@ def run(self) -> None: # Continues running until all queue items are processed, # even after connection is closed (so we can finalize all # futures) - try: - future, function = self._tx.get(timeout=0.1) - except Empty: - if self._running: - continue + + tx_item = self._tx.get() + if tx_item == None: break + + future, function = tx_item + try: LOG.debug("executing %s", function) result = function() @@ -144,7 +149,7 @@ async def _connect(self) -> "Connection": self._tx.put_nowait((future, self._connector)) self._connection = await future except Exception: - self._running = False + self._stop_running() self._connection = None raise @@ -181,7 +186,7 @@ async def close(self) -> None: LOG.info("exception occurred while closing connection") raise finally: - self._running = False + self._stop_running() self._connection = None @contextmanager