Skip to content
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
5 changes: 3 additions & 2 deletions Lib/asyncio/locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ def __repr__(self):
return f'<{res[1:-1]} [{extra}]>'

def locked(self):
"""Return True if lock is acquired."""
return self._locked
"""Return True if lock is acquired or if there are active waiters."""
return not self._locked or (
any(not w.cancelled() for w in (self._waiters or ())))

async def acquire(self):
"""Acquire a lock.
Expand Down
15 changes: 14 additions & 1 deletion Lib/test/test_asyncio/test_locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ async def lockit(name, blocker):
tb.cancel()
self.assertTrue(lock._waiters[0].cancelled())
await asyncio.sleep(0)
self.assertFalse(lock.locked())
self.assertTrue(lock.locked())
self.assertTrue(ta.done())
self.assertTrue(tb.cancelled())
await tc
Expand Down Expand Up @@ -272,6 +272,19 @@ async def test_release_no_waiters(self):
lock.release()
self.assertFalse(lock.locked())

async def test_locked_with_waiters(self):
lock = asyncio.Lock()

await lock.acquire()
waiter = asyncio.create_task(lock.acquire())
await asyncio.sleep(0)

lock.release()
self.assertTrue(lock.locked())

# Cleanup
await waiter

async def test_context_manager(self):
lock = asyncio.Lock()
self.assertFalse(lock.locked())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:meth:`asyncio.Lock.locked` now returns ``True`` when it has active waiters.
Contributed by Emerson Beckwith.
Loading