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

Remove potential dead lock when pending limit is exceeded. #297

Closed
Closed
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions CHANGES/290.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Remove potential dead lock when pending limit is exceeded.
5 changes: 4 additions & 1 deletion aiojobs/_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def __init__(self, *, close_timeout, limit, pending_limit, exception_handler):
self._failed_task = loop.create_task(self._wait_failed())
self._pending = asyncio.Queue(maxsize=pending_limit)
self._closed = False
self._blocked_pending = 0

def __iter__(self):
return iter(list(self._jobs))
Expand Down Expand Up @@ -52,7 +53,7 @@ def close_timeout(self):

@property
def active_count(self):
return len(self._jobs) - self._pending.qsize()
return len(self._jobs) - self._pending.qsize() - self._blocked_pending

@property
def pending_count(self):
Expand All @@ -72,7 +73,9 @@ async def spawn(self, coro):
job._start()
else:
# wait for free slot in queue
self._blocked_pending += 1
await self._pending.put(job)
self._blocked_pending -= 1
return job

async def close(self):
Expand Down
20 changes: 20 additions & 0 deletions tests/test_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from contextlib import suppress
from unittest import mock

import async_timeout
import pytest


Expand Down Expand Up @@ -89,6 +90,25 @@ async def coro2():
assert "pending" not in repr(job2)


async def test_job_deadlock_non_reg(make_scheduler):
async def coro(id, timeout):
print(f"Start coro #{id} with timeout {timeout}", flush=True)
await asyncio.sleep(timeout)
print(f"End coro #{id} with timeout {timeout}", flush=True)

scheduler = await make_scheduler(limit=1, pending_limit=1)
last_job = None
async with async_timeout.timeout(10):
for i in range(3):
# spawn jobs
last_job = await scheduler.spawn(coro(i, 2))

assert last_job
await last_job.wait()
# gracefully close spawned jobs
await scheduler.close()


async def test_job_wait_result(make_scheduler):
handler = mock.Mock()
scheduler = await make_scheduler(exception_handler=handler)
Expand Down