Skip to content

Commit fae2694

Browse files
bpo-45274: Fix Thread._wait_for_tstate_lock() race condition (GH-28532) (GH-28580)
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. (cherry picked from commit a22be49) Co-authored-by: Victor Stinner <[email protected]>
1 parent d452b29 commit fae2694

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
@@ -1100,11 +1100,24 @@ def _wait_for_tstate_lock(self, block=True, timeout=-1):
11001100
# If the lock is acquired, the C code is done, and self._stop() is
11011101
# called. That sets ._is_stopped to True, and ._tstate_lock to None.
11021102
lock = self._tstate_lock
1103-
if lock is None: # already determined that the C code is done
1103+
if lock is None:
1104+
# already determined that the C code is done
11041105
assert self._is_stopped
1105-
elif lock.acquire(block, timeout):
1106-
lock.release()
1107-
self._stop()
1106+
return
1107+
1108+
try:
1109+
if lock.acquire(block, timeout):
1110+
lock.release()
1111+
self._stop()
1112+
except:
1113+
if lock.locked():
1114+
# bpo-45274: lock.acquire() acquired the lock, but the function
1115+
# was interrupted with an exception before reaching the
1116+
# lock.release(). It can happen if a signal handler raises an
1117+
# exception, like CTRL+C which raises KeyboardInterrupt.
1118+
lock.release()
1119+
self._stop()
1120+
raise
11081121

11091122
@property
11101123
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)