Skip to content
Open
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
6 changes: 5 additions & 1 deletion Doc/library/asyncio-sync.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,11 @@ Lock

.. method:: locked()

Return ``True`` if the lock is *locked*.
Return ``True`` if the lock can not be acquired immediately.

.. versionchanged:: next
Also return ``True`` if the lock is *unlocked* but other tasks are
waiting to acquire it.


Event
Expand Down
6 changes: 4 additions & 2 deletions Lib/asyncio/locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,10 @@ 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 cannot be acquired immediately."""
# Due to state, or FIFO rules (must allow others to run first).
return self._locked or (
any(not w.cancelled() for w in (self._waiters or ())))

async def acquire(self):
"""Acquire a lock.
Expand Down
29 changes: 28 additions & 1 deletion Lib/test/test_asyncio/test_locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,12 @@ async def lockit(name, blocker):
tb.cancel()
self.assertTrue(lock._waiters[0].cancelled())
await asyncio.sleep(0)
self.assertFalse(lock.locked())
# A released the lock, and it is now reserved for C.
self.assertTrue(lock.locked())
self.assertTrue(ta.done())
self.assertTrue(tb.cancelled())
await tc
self.assertFalse(lock.locked())

async def test_cancel_release_race(self):
# Issue 32734
Expand Down Expand Up @@ -272,6 +274,31 @@ 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()

t1 = asyncio.create_task(lock.acquire())
t2 = asyncio.create_task(lock.acquire())
await asyncio.sleep(0)
self.assertEqual(len(lock._waiters), 2)

# The lock is released, but it is reserved for the first waiter.
lock.release()
self.assertIs(lock.locked(), True)

await t1
self.assertIs(lock.locked(), True)

# A cancelled waiter does not keep the lock locked.
t2.cancel()
lock.release()
self.assertIs(lock.locked(), False)

with self.assertRaises(asyncio.CancelledError):
await t2
self.assertIs(lock.locked(), False)

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,4 @@
Fix :meth:`asyncio.Lock.locked` returning ``False`` for a lock that has been
released while other tasks are still waiting to acquire it. It now returns
``True`` whenever the lock cannot be acquired immediately, like
:meth:`asyncio.Semaphore.locked`.
Loading