Skip to content

gh-134323: Fix the new threading.RLock.locked method #134368

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

Merged
merged 10 commits into from
May 22, 2025
Merged
Show file tree
Hide file tree
Changes from 7 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: 19 additions & 0 deletions Lib/test/lock_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,25 @@ def test_locked(self):
lock.release()
self.assertFalse(lock.locked())

def test_locked_2threads(self):
# see gh-134323: check that a rlock which
# is acquired in a secaondary thread,
# is still locked in the main thread.
l = []
rlock = self.locktype()
self.assertFalse(rlock.locked())
def acquire():
l.append(rlock.locked())
rlock.acquire()
l.append(rlock.locked())

with Bunch(acquire, 1):
pass
self.assertTrue(rlock.locked())
self.assertFalse(l[0])
self.assertTrue(l[1])
del rlock

def test_release_save_unacquired(self):
# Cannot _release_save an unacquired lock
lock = self.locktype()
Expand Down
2 changes: 1 addition & 1 deletion Lib/threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def __exit__(self, t, v, tb):

def locked(self):
"""Return whether this object is locked."""
return self._count > 0
return self._block.locked()

# Internal methods used by condition variables

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix the :meth:`threading.RLock.locked` method.
13 changes: 12 additions & 1 deletion Modules/_threadmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,13 @@ rlock_traverse(PyObject *self, visitproc visit, void *arg)
return 0;
}

/*
helper function used by rlock_locked and rlock_repr.
*/
static int
rlock_locked_impl(rlockobject *self) {
return PyMutex_IsLocked(&self->lock.mutex);
}

static void
rlock_dealloc(PyObject *self)
Expand Down Expand Up @@ -1110,8 +1117,12 @@ Release the lock.");
static PyObject *
rlock_locked(PyObject *op, PyObject *Py_UNUSED(ignored))
{
/*
see gh-134323: the `_PyRecursiveMutex_IsLocked` function does not exist, so we cast the `op`
to `lockobject` in order to call `PyMutex_IsLocked`.
*/
rlockobject *self = rlockobject_CAST(op);
int is_locked = _PyRecursiveMutex_IsLockedByCurrentThread(&self->lock);
int is_locked = rlock_locked_impl(self);
return PyBool_FromLong(is_locked);
}

Expand Down
Loading