Skip to content

Commit 24c7bbf

Browse files
[3.14] gh-162647: Fix tkinter mainloop() with Tcl interpreters in different threads (GH-162649) (GH-162685)
quit() now stops only the mainloop() of its interpreter, and wakes it up if it is called from other thread. An exception raised in a callback is now only raised by an event loop in the same thread. (cherry picked from commit 0a1d601) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7419cc1 commit 24c7bbf

5 files changed

Lines changed: 146 additions & 26 deletions

File tree

‎Lib/test/test_tkinter/test_misc.py‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,17 @@
44
import sys
55
import textwrap
66
import threading
7+
import time
78
import unittest
89
import weakref
10+
import _tkinter
911
import tkinter
1012
from tkinter import TclError
1113
import enum
1214
from test import support
1315
from test.support import import_helper
1416
from test.support import os_helper
17+
from test.support import threading_helper
1518
from test.support.isolation import runInSubprocess
1619
from test.support.script_helper import assert_python_ok
1720
from test.test_tkinter.support import setUpModule # noqa: F401
@@ -816,6 +819,99 @@ def test_embedded_null(self):
816819
self.assertEqual(widget.selection_get(), '\u20ac\0abc\x00def')
817820

818821

822+
def tcl_is_threaded():
823+
return (tcl_version >= (9,) or
824+
tkinter.Tcl().eval('info exists tcl_platform(threaded)') == '1')
825+
826+
827+
@unittest.skipIf(sys.platform == 'darwin',
828+
'Tk only works in the main thread on macOS')
829+
@unittest.skipUnless(tcl_is_threaded(), 'requires Tcl with thread support')
830+
@threading_helper.requires_working_threading()
831+
class MainloopThreadsTest(unittest.TestCase):
832+
# gh-162647: The mainloop() of Tcl interpreters in different threads
833+
# should not affect each other.
834+
835+
def setUp(self):
836+
# Tk objects created in other threads must not become the default
837+
# root.
838+
self.addCleanup(setattr, tkinter, '_support_default_root',
839+
tkinter._support_default_root)
840+
tkinter._support_default_root = False
841+
self.roots = {}
842+
self.results = []
843+
844+
def mainloop_thread(self, name, ticking=False):
845+
# Return a thread which runs mainloop() of a new Tk.
846+
def run():
847+
root = tkinter.Tk()
848+
root.withdraw()
849+
if ticking:
850+
def tick():
851+
root.after(20, tick)
852+
tick()
853+
self.roots[name] = root
854+
try:
855+
root.mainloop()
856+
self.results.append((name, None))
857+
except BaseException as e:
858+
self.results.append((name, e))
859+
finally:
860+
# The interpreter should be deleted in its thread.
861+
del self.roots[name]
862+
root.destroy()
863+
del root
864+
return threading.Thread(target=run)
865+
866+
def wait_mainloop(self, name):
867+
for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
868+
if name in self.roots:
869+
break
870+
# A call from other thread waits until mainloop() runs.
871+
self.roots[name].tk.call('info', 'patchlevel')
872+
873+
def quit_all(self):
874+
for root in list(self.roots.values()):
875+
root.quit()
876+
877+
# Run in a subprocess, since thread-specific Tcl data is not cleaned up.
878+
@runInSubprocess(timeout=support.SHORT_TIMEOUT)
879+
def test_quit(self):
880+
threads = [self.mainloop_thread('a'),
881+
self.mainloop_thread('b', ticking=True)]
882+
with threading_helper.start_threads(threads, unlock=self.quit_all):
883+
self.wait_mainloop('a')
884+
self.wait_mainloop('b')
885+
# quit() stops the mainloop() of its interpreter even if it
886+
# waits for events, and does not stop other mainloop().
887+
self.roots['a'].quit()
888+
threads[0].join(support.SHORT_TIMEOUT)
889+
self.assertEqual(self.results, [('a', None)])
890+
self.assertEqual(self.results, [('a', None), ('b', None)])
891+
892+
@runInSubprocess(timeout=support.SHORT_TIMEOUT)
893+
def test_callback_error(self):
894+
threads = [self.mainloop_thread('b', ticking=True)]
895+
with threading_helper.start_threads(threads, unlock=self.quit_all):
896+
self.wait_mainloop('b')
897+
root = tkinter.Tk()
898+
self.addCleanup(root.destroy)
899+
root.withdraw()
900+
def callback():
901+
raise ZeroDivisionError
902+
root.tk.createcommand('callback', callback)
903+
root.tk.call('after', 0, 'callback')
904+
root.update()
905+
# Let the mainloop() in other thread run for a while.
906+
time.sleep(0.2)
907+
# The error was not raised in other thread...
908+
self.assertEqual(self.results, [('b', None)])
909+
# ...but by the next mainloop() in this thread.
910+
root.after(100, root.quit)
911+
with self.assertRaises(ZeroDivisionError):
912+
root.mainloop()
913+
914+
819915
class TkTest(AbstractTkTest, unittest.TestCase):
820916

821917
def test_className(self):
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix :mod:`tkinter` when Tcl interpreters run :meth:`!mainloop` in different
2+
threads. :meth:`!quit` no longer stops the main loop of other interpreter,
3+
and stops the main loop even if it waits for events. An exception raised in
4+
a callback is no longer raised by the main loop in other thread.

‎Modules/_tkinter.c‎

Lines changed: 45 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ Copyright (C) 1994 Steen Lumholt.
3131
#endif
3232

3333
#include "pycore_long.h" // _PyLong_IsNegative()
34+
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_INT_RELAXED()
3435
#include "pycore_sysmodule.h" // _PySys_GetOptionalAttrString()
3536
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8String
3637

@@ -407,6 +408,7 @@ typedef struct {
407408
int threaded; /* True if tcl_platform[threaded] */
408409
Tcl_ThreadId thread_id;
409410
int dispatching;
411+
int quitting; /* Set by quit() to stop mainloop() */
410412
int event_hook; /* True if counted by EnableEventHook() */
411413
PyObject *trace;
412414
/* We cannot include tclInt.h, as this is internal.
@@ -449,9 +451,14 @@ check_tcl_appartment(TkappObject *app)
449451
/**** Error Handling ****/
450452

451453
static PyObject *Tkinter_TclError;
452-
static int quitMainLoop = 0;
453-
static int errorInCmd = 0;
454-
static PyObject *excInCmd;
454+
455+
/* An exception raised in a Python callback, which should be raised by the
456+
event loop (mainloop() or the event hook) that called the callback.
457+
Callbacks are only called in the thread of their Tcl interpreter, so it
458+
is thread-local. */
459+
static Tcl_ThreadDataKey excInCmd_key;
460+
#define excInCmd \
461+
(*(PyObject **)Tcl_GetThreadData(&excInCmd_key, sizeof(PyObject *)))
455462

456463

457464
static PyObject *Tkapp_UnicodeResult(TkappObject *);
@@ -2521,8 +2528,7 @@ PythonCmd(ClientData clientData, Tcl_Interp *interp,
25212528
goto done;
25222529

25232530
error:
2524-
errorInCmd = 1;
2525-
excInCmd = PyErr_GetRaisedException();
2531+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
25262532
done:
25272533
LEAVE_PYTHON
25282534

@@ -2760,8 +2766,7 @@ FileHandler(ClientData clientData, int mask)
27602766

27612767
res = PyObject_CallFunction(func, "Oi", file, mask);
27622768
if (res == NULL) {
2763-
errorInCmd = 1;
2764-
excInCmd = PyErr_GetRaisedException();
2769+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
27652770
}
27662771
Py_XDECREF(res);
27672772
LEAVE_PYTHON
@@ -2939,8 +2944,7 @@ TimerHandler(ClientData clientData)
29392944
Py_DECREF(v); /* See Tktt_New() */
29402945

29412946
if (res == NULL) {
2942-
errorInCmd = 1;
2943-
excInCmd = PyErr_GetRaisedException();
2947+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
29442948
}
29452949
else
29462950
Py_DECREF(res);
@@ -3005,10 +3009,10 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold)
30053009
int dispatching = self->dispatching;
30063010
self->dispatching = 1;
30073011

3008-
quitMainLoop = 0;
3012+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 0);
30093013
while (Tk_GetNumMainWindows() > threshold &&
3010-
!quitMainLoop &&
3011-
!errorInCmd)
3014+
!FT_ATOMIC_LOAD_INT_RELAXED(self->quitting) &&
3015+
excInCmd == NULL)
30123016
{
30133017
int result;
30143018

@@ -3038,12 +3042,12 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold)
30383042
break;
30393043
}
30403044
self->dispatching = dispatching;
3041-
quitMainLoop = 0;
3045+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 0);
30423046

3043-
if (errorInCmd) {
3044-
errorInCmd = 0;
3045-
PyErr_SetRaisedException(excInCmd);
3047+
PyObject *exc = excInCmd;
3048+
if (exc != NULL) {
30463049
excInCmd = NULL;
3050+
PyErr_SetRaisedException(exc);
30473051
return NULL;
30483052
}
30493053
Py_RETURN_NONE;
@@ -3069,6 +3073,13 @@ _tkinter_tkapp_dooneevent_impl(TkappObject *self, int flags)
30693073
return PyLong_FromLong(rv);
30703074
}
30713075

3076+
static int
3077+
QuitEventProc(Tcl_Event *evPtr, int flags)
3078+
{
3079+
/* Nothing to do: the event only wakes up the event loop. */
3080+
return 1;
3081+
}
3082+
30723083
/*[clinic input]
30733084
_tkinter.tkapp.quit
30743085
[clinic start generated code]*/
@@ -3077,7 +3088,21 @@ static PyObject *
30773088
_tkinter_tkapp_quit_impl(TkappObject *self)
30783089
/*[clinic end generated code: output=7f21eeff481f754f input=e03020dc38aff23c]*/
30793090
{
3080-
quitMainLoop = 1;
3091+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 1);
3092+
if (self->threaded && self->dispatching &&
3093+
self->thread_id != Tcl_GetCurrentThread())
3094+
{
3095+
/* mainloop() is running in other thread and can wait for an event.
3096+
Send it an event, so that it checks the flag. */
3097+
Tcl_Event *ev = (Tcl_Event *)attemptckalloc(sizeof(Tcl_Event));
3098+
if (ev == NULL) {
3099+
return PyErr_NoMemory();
3100+
}
3101+
memset(ev, 0, sizeof(Tcl_Event));
3102+
ev->proc = QuitEventProc;
3103+
Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL);
3104+
Tcl_ThreadAlert(self->thread_id);
3105+
}
30813106
Py_RETURN_NONE;
30823107
}
30833108

@@ -3551,7 +3576,6 @@ EventHook(void)
35513576
stdin_ready = 0;
35523577
#endif
35533578
PyEval_RestoreThread(tstate);
3554-
errorInCmd = 0;
35553579
#ifdef MS_WINDOWS
35563580
hStdin = GetStdHandle(STD_INPUT_HANDLE);
35573581
type = GetFileType(hStdin);
@@ -3609,10 +3633,10 @@ EventHook(void)
36093633
instead of returning to the prompt: without readline there is no
36103634
input waiting on stdin yet, so returning here would block in fgets
36113635
until the user hits enter, freezing later callbacks. */
3612-
if (errorInCmd) {
3613-
errorInCmd = 0;
3614-
PyErr_SetRaisedException(excInCmd);
3636+
PyObject *exc = excInCmd;
3637+
if (exc != NULL) {
36153638
excInCmd = NULL;
3639+
PyErr_SetRaisedException(exc);
36163640
PyErr_Print();
36173641
}
36183642
if (result < 0)

‎Tools/c-analyzer/cpython/globals-to-fix.tsv‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -397,9 +397,6 @@ Modules/xxmodule.c - ErrorObject -
397397
## state
398398
Modules/_datetimemodule.c - _datetime_global_state -
399399
Modules/_tkinter.c - tcl_lock -
400-
Modules/_tkinter.c - excInCmd -
401-
Modules/_tkinter.c - valInCmd -
402-
Modules/_tkinter.c - trbInCmd -
403400

404401

405402
##################################
@@ -429,8 +426,6 @@ Modules/readline.c - libedit_history_start -
429426
Modules/_ctypes/malloc_closure.c - free_list -
430427
Modules/_curses_panel.c - lop -
431428
Modules/_ssl/debughelpers.c _PySSL_keylog_callback lock -
432-
Modules/_tkinter.c - quitMainLoop -
433-
Modules/_tkinter.c - errorInCmd -
434429
Modules/_tkinter.c - Tkinter_busywaitinterval -
435430
Modules/_tkinter.c - call_mutex -
436431
Modules/_tkinter.c - var_mutex -

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,7 @@ Modules/_struct.c - bigendian_table -
258258
Modules/_struct.c - lilendian_table -
259259
Modules/_struct.c - native_table -
260260
Modules/_tkinter.c - state_key -
261+
Modules/_tkinter.c - excInCmd_key -
261262
Modules/_interpchannelsmodule.c - _channelid_end_recv -
262263
Modules/_interpchannelsmodule.c - _channelid_end_send -
263264
Modules/_zoneinfo.c - DAYS_BEFORE_MONTH -

0 commit comments

Comments
 (0)