Skip to content

Commit f16b34a

Browse files
gh-162724: Free per-thread Tcl resources at thread exit in tkinter (GH-162725)
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.
1 parent 5b6dd1e commit f16b34a

5 files changed

Lines changed: 64 additions & 7 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 & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,7 +1042,6 @@ def tick():
10421042
del self.roots[name]
10431043
root.destroy()
10441044
del root
1045-
_tkinter._finalize_thread()
10461045
return threading.Thread(target=run)
10471046

10481047
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
@@ -416,6 +416,50 @@ static Tcl_ThreadDataKey excInCmd_key;
416416
#define excInCmd \
417417
(*(PyObject **)Tcl_GetThreadData(&excInCmd_key, sizeof(PyObject *)))
418418

419+
/* The number of live Tcl interpreters created in the current thread. */
420+
static Tcl_ThreadDataKey interp_count_key;
421+
#define interp_count \
422+
(*(int *)Tcl_GetThreadData(&interp_count_key, sizeof(int)))
423+
424+
/* Tcl allocates per-thread resources (for example an event handle on
425+
Windows for every thread which waits for a call to a Tcl interpreter in
426+
other thread), which are only freed by Tcl_FinalizeThread(). Call it
427+
when the Python thread state is cleared at the end of the thread, unless
428+
the thread still has a Tcl interpreter. */
429+
430+
#define THREAD_FINALIZER_NAME "_tkinter.thread_finalizer"
431+
432+
static void
433+
thread_finalizer(PyObject *capsule)
434+
{
435+
void *thread_id = PyCapsule_GetPointer(capsule, THREAD_FINALIZER_NAME);
436+
if (thread_id == (void *)Tcl_GetCurrentThread() && interp_count == 0) {
437+
Tcl_FinalizeThread();
438+
}
439+
}
440+
441+
static int
442+
register_thread_finalizer(void)
443+
{
444+
PyObject *dict = PyThreadState_GetDict();
445+
if (dict == NULL) {
446+
return 0;
447+
}
448+
int r = PyDict_ContainsString(dict, THREAD_FINALIZER_NAME);
449+
if (r != 0) {
450+
return r < 0 ? -1 : 0;
451+
}
452+
PyObject *capsule = PyCapsule_New((void *)Tcl_GetCurrentThread(),
453+
THREAD_FINALIZER_NAME,
454+
thread_finalizer);
455+
if (capsule == NULL) {
456+
return -1;
457+
}
458+
r = PyDict_SetItemString(dict, THREAD_FINALIZER_NAME, capsule);
459+
Py_DECREF(capsule);
460+
return r;
461+
}
462+
419463

420464
static PyObject *Tkapp_UnicodeResult(TkappObject *);
421465

@@ -670,6 +714,11 @@ Tkapp_New(const char *screenName, const char *className,
670714
v->interp = Tcl_CreateInterp();
671715
PyMutex_Unlock(&tcl_create_mutex);
672716
v->thread_id = Tcl_GetCurrentThread();
717+
interp_count++;
718+
if (register_thread_finalizer() < 0) {
719+
Py_DECREF(v);
720+
return NULL;
721+
}
673722
#if TCL_MAJOR_VERSION < 9 /* Tcl 9.x is always threaded */
674723
threaded = Tcl_GetVar2Ex(v->interp,
675724
"tcl_platform",
@@ -1745,6 +1794,9 @@ _tkinter_tkapp_call_impl(TkappObject *self, PyObject *args)
17451794
PyObject *exc = NULL; // init to make static analyzers happy
17461795
if (!WaitForMainloop(self))
17471796
return NULL;
1797+
if (register_thread_finalizer() < 0) {
1798+
return NULL;
1799+
}
17481800
ev = (Tkapp_CallEvent*)attemptckalloc(sizeof(Tkapp_CallEvent));
17491801
if (ev == NULL) {
17501802
PyErr_NoMemory();
@@ -2026,6 +2078,9 @@ var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags)
20262078
if (!WaitForMainloop(self))
20272079
return NULL;
20282080

2081+
if (register_thread_finalizer() < 0) {
2082+
return NULL;
2083+
}
20292084
ev = (VarEvent*)attemptckalloc(sizeof(VarEvent));
20302085
if (ev == NULL) {
20312086
PyErr_NoMemory();
@@ -2705,7 +2760,7 @@ _tkinter_tkapp_createcommand_impl(TkappObject *self, const char *name,
27052760
}
27062761

27072762
if (self->thread_id != Tcl_GetCurrentThread() &&
2708-
!WaitForMainloop(self))
2763+
(!WaitForMainloop(self) || register_thread_finalizer() < 0))
27092764
return NULL;
27102765

27112766
TRACE(self, ("((ss()O))", "proc", name, func));
@@ -2781,6 +2836,9 @@ _tkinter_tkapp_deletecommand_impl(TkappObject *self, const char *name)
27812836

27822837
Tcl_Condition cond = NULL;
27832838
CommandEvent *ev;
2839+
if (register_thread_finalizer() < 0) {
2840+
return NULL;
2841+
}
27842842
ev = (CommandEvent*)attemptckalloc(sizeof(CommandEvent));
27852843
if (ev == NULL) {
27862844
PyErr_NoMemory();
@@ -3385,6 +3443,7 @@ Tkapp_Dealloc(PyObject *op)
33853443
ENTER_TCL
33863444
Tcl_DeleteInterp(Tkapp_Interp(self));
33873445
LEAVE_TCL
3446+
interp_count--;
33883447
}
33893448
DisableEventHook(self);
33903449
(void)Tkapp_Clear(op);

‎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)