8000 bpo-37788: Fix a reference leak if a thread is not joined. by shihai1991 · Pull Request #25226 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

bpo-37788: Fix a reference leak if a thread is not joined. #25226

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
add _discard_shutdown_lock() in threading module
  • Loading branch information
shihai1991 committed Apr 8, 2021
commit 213cd7727ac8badd6efc4737baee10c463c530ae
14 changes: 14 additions & 0 deletions Lib/test/test_threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,20 @@ def noop(): pass
threading.Thread(target=noop).start()
# Thread.join() is not called

def test_leak_without_join_2(self):
# Same as above, but a delay gets introduced after the thread's
# Python code returned but before the thread state is deleted.
def random_sleep():
seconds = random.random() * 0.010
time.sleep(seconds)

def f():
random_sleep()

with threading_helper.wait_threads_exit():
threading.Thread(target=f).start()
# Thread.join() is not called


class ThreadJoinOnShutdown(BaseTestCase):

Expand Down
17 changes: 7 additions & 10 deletions Lib/threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -839,16 +839,6 @@ class is implemented.
# For debugging and _after_fork()
_dangling.add(self)

def __del__(self):
if not self._initialized:
return
lock = self._tstate_lock
if lock is not None and not self.daemon:
if lock.acquire(False):
lock.release()
with _shutdown_locks_lock:
_shutdown_locks.discard(lock)

def _reset_internal_locks(self, is_alive):
# private! Called by _after_fork() to reset our internal locks as
# they may be in an invalid state leading to a deadlock or crash.
Expand Down Expand Up @@ -1417,6 +1407,13 @@ def _register_atexit(func, *arg, **kwargs):

_main_thread = _MainThread()

def _discard_shutdown_lock(lock):
"""
Discard the Thread._tstate_lock lock when the non-daemon thread have done.
"""
with _shutdown_locks_lock:
_shutdown_locks.discard(lock)

def _shutdown():
"""
Wait until the Python thread state of all non-daemon threads get deleted.
Expand Down
25 changes: 24 additions & 1 deletion Modules/_threadmodule.c
483E
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
/* Interface to Sjoerd's portable C thread library */

#include "Python.h"
#include "pycore_pylifecycle.h"
#include "pycore_interp.h" // _PyInterpreterState.num_threads
#include "pycore_pyerrors.h" // _PyErr_Occurred()
#include "pycore_pylifecycle.h"
#include "pycore_pystate.h" // _PyThreadState_Init()
#include <stddef.h> // offsetof()
#include "structmember.h" // PyMemberDef
Expand All @@ -20,6 +21,7 @@ _Py_IDENTIFIER(__dict__);

_Py_IDENTIFIER(stderr);
_Py_IDENTIFIER(flush);
_Py_IDENTIFIER(threading);


// Forward declarations
Expand Down Expand Up @@ -1277,19 +1279,40 @@ In most applications `threading.enumerate()` should be used instead.");
static void
release_sentinel(void *wr_raw)
{
_Py_IDENTIFIER(_discard_shutdown_lock);
PyObject *wr = _PyObject_CAST(wr_raw);
/* Tricky: this function is called when the current thread state
is being deleted. Therefore, only simple C code can safely
execute here. */
PyObject *obj = PyWeakref_GET_OBJECT(wr);
lockobject *lock;

if (obj != Py_None) {
lock = (lockobject *) obj;
if (lock->locked) {
PyThread_release_lock(lock->lock_lock);
lock->locked = 0;
}
PyThreadState *tstate = _PyThreadState_GET();
PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
if (threading == NULL) {
if (!_PyErr_Occurred(tstate)) {
_PyErr_SetString(tstate, PyExc_RuntimeError,
"lost threading module");
}
goto exit;
}
PyObject *result = _PyObject_CallMethodIdOneArg(
threading, &PyId__discard_shutdown_lock, obj);
if (result == NULL) {
PyErr_WriteUnraisable(threading);
} else {
Py_DECREF(result);
}
Py_DECREF(threading);
}

exit:
/* Deallocating a weakref with a NULL callback only calls
PyObject_GC_Del(), which can't call any Python code. */
Py_DECREF(wr);
Expand Down
0