This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: asyncio lock does not get released after task is canceled
Type: behavior Stage: resolved
Components: asyncio Versions:
process
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: a.niederbuehl, asvetlov, jaswdr, yselivanov
Priority: normal Keywords:

Created on 2021-04-30 18:49 by a.niederbuehl, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg392499 - (view) Author: Alexander Niederbühl (a.niederbuehl) Date: 2021-04-30 18:49
If a task gets canceled while holding a lock, the lock is not automatically released. Is that expected, it seems like it could cause a deadlock?

Failing test adapted from Lib/test/test_asyncio/test_locks.py (commit 6bd9288b80):

    def test_acquire_cancel(self):
        lock = asyncio.Lock()
        self.assertTrue(self.loop.run_until_complete(lock.acquire()))

        task = self.loop.create_task(lock.acquire())
        self.loop.call_soon(task.cancel)
        self.assertRaises(
            asyncio.CancelledError,
            self.loop.run_until_complete, task)
        self.assertFalse(lock._waiters)

        # Should the lock get released after cancellation?
        self.assertFalse(lock.locked())

I stumbled upon this while playing around with TLA+.
msg392822 - (view) Author: Jonathan Schweder (jaswdr) * Date: 2021-05-03 16:50
a.niederbuehl tasks are free of context, meaning that the task does not know what was done inside it, and by consequence is impossible to know when or not release a lock. This is by design and normally in these cases you need to be aware of the lock, by for example checking if the lock was released before cancelling the task.
msg392842 - (view) Author: Alexander Niederbühl (a.niederbuehl) Date: 2021-05-03 21:13
That makes sense, thanks!
History
Date User Action Args
2022-04-11 14:59:44adminsetgithub: 88157
2021-05-03 21:13:22a.niederbuehlsetstatus: open -> closed

messages: + msg392842
stage: resolved
2021-05-03 16:50:29jaswdrsetnosy: + jaswdr
messages: + msg392822
2021-04-30 18:49:44a.niederbuehlcreate