Skip to content

Commit b44bb7a

Browse files
[3.15] gh-162724: Free per-thread Tcl resources at thread exit in tkinter (GH-162725) (GH-163152)
Call Tcl_FinalizeThread() when the Python thread state is cleared at the end of a thread which made calls to a Tcl interpreter in other thread or created a Tcl interpreter, unless the thread still has a Tcl interpreter. This fixes a leak of an event handle on Windows for every such thread. The explicit _tkinter._finalize_thread() calls in tests are no longer needed. (cherry picked from commit f16b34a)
1 parent 646cbf6 commit b44bb7a

5 files changed

Lines changed: 64 additions & 8 deletions

File tree

‎Lib/test/test_tcl.py‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -621,11 +621,6 @@ def test_returning_deeply_nested(self):
621621
interp.eval('set x a; for {set i 0} {$i < %d} {incr i} {set x [list $x]}'
622622
% support.exceeds_recursion_limit())
623623
self.assertRaises(RecursionError, interp.getvar, 'x')
624-
interp = None
625-
626-
# gh-161353: Clean up explicitly per-thread state to avoid leaking an
627-
# event handle on Windows when test_tcl is run with -R 3:3 option.
628-
_tkinter._finalize_thread()
629624

630625
def test_setvar_evil(self):
631626
# gh-161388

‎Lib/test/test_tkinter/test_misc.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import time
1010
import unittest
1111
import weakref
12-
import _tkinter
1312
import tkinter
1413
from tkinter import TclError
1514
import enum
@@ -874,7 +873,6 @@ def tick():
874873
del self.roots[name]
875874
root.destroy()
876875
del root
877-
_tkinter._finalize_thread()
878876
return threading.Thread(target=run)
879877

880878
def wait_mainloop(self, name):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a leak of per-thread Tcl resources (an event handle on Windows) in
2+
:mod:`tkinter` when a thread which made calls to a Tcl interpreter in other
3+
thread, or which created a Tcl interpreter, exits.

‎Modules/_tkinter.c‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,50 @@ static Tcl_ThreadDataKey excInCmd_key;
435435
#define excInCmd \
436436
(*(PyObject **)Tcl_GetThreadData(&excInCmd_key, sizeof(PyObject *)))
437437

438+
/* The number of live Tcl interpreters created in the current thread. */
439+
static Tcl_ThreadDataKey interp_count_key;
440+
#define interp_count \
441+
(*(int *)Tcl_GetThreadData(&interp_count_key, sizeof(int)))
442+
443+
/* Tcl allocates per-thread resources (for example an event handle on
444+
Windows for every thread which waits for a call to a Tcl interpreter in
445+
other thread), which are only freed by Tcl_FinalizeThread(). Call it
446+
when the Python thread state is cleared at the end of the thread, unless
447+
the thread still has a Tcl interpreter. */
448+
449+
#define THREAD_FINALIZER_NAME "_tkinter.thread_finalizer"
450+
451+
static void
452+
thread_finalizer(PyObject *capsule)
453+
{
454+
void *thread_id = PyCapsule_GetPointer(capsule, THREAD_FINALIZER_NAME);
455+
if (thread_id == (void *)Tcl_GetCurrentThread() && interp_count == 0) {
456+
Tcl_FinalizeThread();
457+
}
458+
}
459+
460+
static int
461+
register_thread_finalizer(void)
462+
{
463+
PyObject *dict = PyThreadState_GetDict();
464+
if (dict == NULL) {
465+
return 0;
466+
}
467+
int r = PyDict_ContainsString(dict, THREAD_FINALIZER_NAME);
468+
if (r != 0) {
469+
return r < 0 ? -1 : 0;
470+
}
471+
PyObject *capsule = PyCapsule_New((void *)Tcl_GetCurrentThread(),
472+
THREAD_FINALIZER_NAME,
473+
thread_finalizer);
474+
if (capsule == NULL) {
475+
return -1;
476+
}
477+
r = PyDict_SetItemString(dict, THREAD_FINALIZER_NAME, capsule);
478+
Py_DECREF(capsule);
479+
return r;
480+
}
481+
438482

439483
static PyObject *Tkapp_UnicodeResult(TkappObject *);
440484

@@ -684,6 +728,7 @@ Tkapp_New(const char *screenName, const char *className,
684728
static PyMutex tcl_create_mutex;
685729
PyMutex_Lock(&tcl_create_mutex);
686730
v->interp = Tcl_CreateInterp();
731+
interp_count++;
687732
v->wantobjects = wantobjects;
688733
#if TCL_MAJOR_VERSION >= 9
689734
v->threaded = 1;
@@ -710,6 +755,10 @@ Tkapp_New(const char *screenName, const char *className,
710755
tcl_lock = NULL;
711756
}
712757
PyMutex_Unlock(&tcl_create_mutex);
758+
if (register_thread_finalizer() < 0) {
759+
Py_DECREF(v);
760+
return NULL;
761+
}
713762

714763
v->OldBooleanType = Tcl_GetObjType("boolean");
715764
{
@@ -1646,6 +1695,9 @@ Tkapp_Call(PyObject *selfptr, PyObject *args)
16461695
PyObject *exc = NULL; // init to make static analyzers happy
16471696
if (!WaitForMainloop(self))
16481697
return NULL;
1698+
if (register_thread_finalizer() < 0) {
1699+
return NULL;
1700+
}
16491701
ev = (Tkapp_CallEvent*)attemptckalloc(sizeof(Tkapp_CallEvent));
16501702
if (ev == NULL) {
16511703
PyErr_NoMemory();
@@ -1927,6 +1979,9 @@ var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags)
19271979
if (!WaitForMainloop(self))
19281980
return NULL;
19291981

1982+
if (register_thread_finalizer() < 0) {
1983+
return NULL;
1984+
}
19301985
ev = (VarEvent*)attemptckalloc(sizeof(VarEvent));
19311986
if (ev == NULL) {
19321987
PyErr_NoMemory();
@@ -2608,7 +2663,7 @@ _tkinter_tkapp_createcommand_impl(TkappObject *self, const char *name,
26082663
}
26092664

26102665
if (self->threaded && self->thread_id != Tcl_GetCurrentThread() &&
2611-
!WaitForMainloop(self))
2666+
(!WaitForMainloop(self) || register_thread_finalizer() < 0))
26122667
return NULL;
26132668

26142669
TRACE(self, ("((ss()O))", "proc", name, func));
@@ -2684,6 +2739,9 @@ _tkinter_tkapp_deletecommand_impl(TkappObject *self, const char *name)
26842739

26852740
Tcl_Condition cond = NULL;
26862741
CommandEvent *ev;
2742+
if (register_thread_finalizer() < 0) {
2743+
return NULL;
2744+
}
26872745
ev = (CommandEvent*)attemptckalloc(sizeof(CommandEvent));
26882746
if (ev == NULL) {
26892747
PyErr_NoMemory();
@@ -3254,6 +3312,7 @@ Tkapp_Dealloc(PyObject *op)
32543312
ENTER_TCL
32553313
Tcl_DeleteInterp(Tkapp_Interp(self));
32563314
LEAVE_TCL
3315+
interp_count--;
32573316
}
32583317
DisableEventHook(self);
32593318
Py_XDECREF(self->trace);

‎Tools/c-analyzer/cpython/ignored.tsv‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ Modules/_struct.c - lilendian_table -
264264
Modules/_struct.c - native_table -
265265
Modules/_tkinter.c - state_key -
266266
Modules/_tkinter.c - excInCmd_key -
267+
Modules/_tkinter.c - interp_count_key -
267268
Modules/_interpchannelsmodule.c - _channelid_end_recv -
268269
Modules/_interpchannelsmodule.c - _channelid_end_send -
269270
Modules/_zoneinfo.c - DAYS_BEFORE_MONTH -

0 commit comments

Comments
 (0)