Skip to content

Commit a22be49

Browse files
authored
bpo-45274: Fix Thread._wait_for_tstate_lock() race condition (GH-28532)
Fix a race condition in the Thread.join() method of the threading module. If the function is interrupted by a signal and the signal handler raises an exception, make sure that the thread remains in a consistent state to prevent a deadlock.
1 parent 7b88f63 commit a22be49

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

Lib/threading.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1094,11 +1094,24 @@ def _wait_for_tstate_lock(self, block=True, timeout=-1):
10941094
# If the lock is acquired, the C code is done, and self._stop() is
10951095
# called. That sets ._is_stopped to True, and ._tstate_lock to None.
10961096
lock = self._tstate_lock
1097-
if lock is None: # already determined that the C code is done
1097+
if lock is None:
1098+
# already determined that the C code is done
10981099
assert self._is_stopped
1099-
elif lock.acquire(block, timeout):
1100-
lock.release()
1101-
self._stop()
1100+
return
1101+
1102+
try:
1103+
if lock.acquire(block, timeout):
1104+
lock.release()
1105+
self._stop()
1106+
except:
1107+
if lock.locked():
1108+
# bpo-45274: lock.acquire() acquired the lock, but the function
1109+
# was interrupted with an exception before reaching the
1110+
# lock.release(). It can happen if a signal handler raises an
1111+
# exception, like CTRL+C which raises KeyboardInterrupt.
1112+
lock.release()
1113+
self._stop()
1114+
raise
11021115

11031116
@property
11041117
def name(self):
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Fix a race condition in the :meth:`Thread.join() <threading.Thread.join>`
2+
method of the :mod:`threading` module. If the function is interrupted by a
3+
signal and the signal handler raises an exception, make sure that the thread
4+
remains in a consistent state to prevent a deadlock. Patch by Victor
5+
Stinner.

0 commit comments

Comments
 (0)