Skip to content

Commit 068d570

Browse files
[3.14] gh-134322: Fix repr(threading.RLock) (GH-134389) (#134528)
gh-134322: Fix `repr(threading.RLock)` (GH-134389) Fix the `__repr__` value of `threading.RLock` from `_thread` module, when just created. (cherry picked from commit fade146) Co-authored-by: Duprat <[email protected]>
1 parent bbf8048 commit 068d570

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

Lib/test/lock_tests.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,26 @@ class RLockTests(BaseLockTests):
332332
"""
333333
Tests for recursive locks.
334334
"""
335+
def test_repr_count(self):
336+
# see gh-134322: check that count values are correct:
337+
# when a rlock is just created,
338+
# in a second thread when rlock is acquired in the main thread.
339+
lock = self.locktype()
340+
self.assertIn("count=0", repr(lock))
341+
self.assertIn("<unlocked", repr(lock))
342+
lock.acquire()
343+
lock.acquire()
344+
self.assertIn("count=2", repr(lock))
345+
self.assertIn("<locked", repr(lock))
346+
347+
result = []
348+
def call_repr():
349+
result.append(repr(lock))
350+
with Bunch(call_repr, 1):
351+
pass
352+
self.assertIn("count=2", result[0])
353+
self.assertIn("<locked", result[0])
354+
335355
def test_reacquire(self):
336356
lock = self.locktype()
337357
lock.acquire()

Lib/test/test_importlib/test_locks.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ class ModuleLockAsRLockTests:
3434
# lock status in repr unsupported
3535
test_repr = None
3636
test_locked_repr = None
37+
test_repr_count = None
3738

3839
def tearDown(self):
3940
for splitinit in init.values():

Modules/_threadmodule.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1208,7 +1208,13 @@ rlock_repr(PyObject *op)
12081208
rlockobject *self = rlockobject_CAST(op);
12091209
PyThread_ident_t owner = self->lock.thread;
12101210
int locked = rlock_locked_impl(self);
1211-
size_t count = self->lock.level + 1;
1211+
size_t count;
1212+
if (locked) {
1213+
count = self->lock.level + 1;
1214+
}
1215+
else {
1216+
count = 0;
1217+
}
12121218
return PyUnicode_FromFormat(
12131219
"<%s %s object owner=%" PY_FORMAT_THREAD_IDENT_T " count=%zu at %p>",
12141220
locked ? "locked" : "unlocked",

0 commit comments

Comments
 (0)