Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce CPU usage in the connection thread loop #213

Merged
merged 1 commit into from
Feb 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions aiosqlite/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down