Skip to content

Commit 0a1d601

Browse files
gh-162647: Fix tkinter mainloop() with Tcl interpreters in different threads (GH-162649)
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. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 03c48b7 commit 0a1d601

5 files changed

Lines changed: 142 additions & 26 deletions

File tree

‎Lib/test/test_tkinter/test_misc.py‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from test import support
1818
from test.support import import_helper
1919
from test.support import os_helper
20+
from test.support import threading_helper
2021
from test.support.isolation import runInSubprocess
2122
from test.support.script_helper import assert_python_ok
2223
from test.test_tkinter.support import setUpModule # noqa: F401
@@ -1005,6 +1006,97 @@ def test_iterable_protocol(self):
10051006
widget in widget
10061007

10071008

1009+
def tcl_is_threaded():
1010+
return (tcl_version >= (9,) or
1011+
tkinter.Tcl().eval('info exists tcl_platform(threaded)') == '1')
1012+
1013+
1014+
@unittest.skipIf(sys.platform == 'darwin',
1015+
'Tk only works in the main thread on macOS')
1016+
@unittest.skipUnless(tcl_is_threaded(), 'requires Tcl with thread support')
1017+
@threading_helper.requires_working_threading()
1018+
class MainloopThreadsTest(unittest.TestCase):
1019+
# gh-162647: The mainloop() of Tcl interpreters in different threads
1020+
# should not affect each other.
1021+
1022+
def setUp(self):
1023+
# Tk objects created in other threads must not become the default
1024+
# root.
1025+
self.addCleanup(setattr, tkinter, '_support_default_root',
1026+
tkinter._support_default_root)
1027+
tkinter._support_default_root = False
1028+
self.roots = {}
1029+
self.results = []
1030+
1031+
def mainloop_thread(self, name, ticking=False):
1032+
# Return a thread which runs mainloop() of a new Tk.
1033+
def run():
1034+
root = tkinter.Tk()
1035+
root.withdraw()
1036+
if ticking:
1037+
def tick():
1038+
root.after(20, tick)
1039+
tick()
1040+
self.roots[name] = root
1041+
try:
1042+
root.mainloop()
1043+
self.results.append((name, None))
1044+
except BaseException as e:
1045+
self.results.append((name, e))
1046+
finally:
1047+
# The interpreter should be deleted in its thread.
1048+
del self.roots[name]
1049+
root.destroy()
1050+
del root
1051+
_tkinter._finalize_thread()
1052+
return threading.Thread(target=run)
1053+
1054+
def wait_mainloop(self, name):
1055+
for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
1056+
if name in self.roots:
1057+
break
1058+
# A call from other thread waits until mainloop() runs.
1059+
self.roots[name].tk.call('info', 'patchlevel')
1060+
1061+
def quit_all(self):
1062+
for root in list(self.roots.values()):
1063+
root.quit()
1064+
1065+
def test_quit(self):
1066+
threads = [self.mainloop_thread('a'),
1067+
self.mainloop_thread('b', ticking=True)]
1068+
with threading_helper.start_threads(threads, unlock=self.quit_all):
1069+
self.wait_mainloop('a')
1070+
self.wait_mainloop('b')
1071+
# quit() stops the mainloop() of its interpreter even if it
1072+
# waits for events, and does not stop other mainloop().
1073+
self.roots['a'].quit()
1074+
threads[0].join(support.SHORT_TIMEOUT)
1075+
self.assertEqual(self.results, [('a', None)])
1076+
self.assertEqual(self.results, [('a', None), ('b', None)])
1077+
1078+
def test_callback_error(self):
1079+
threads = [self.mainloop_thread('b', ticking=True)]
1080+
with threading_helper.start_threads(threads, unlock=self.quit_all):
1081+
self.wait_mainloop('b')
1082+
root = tkinter.Tk()
1083+
self.addCleanup(root.destroy)
1084+
root.withdraw()
1085+
def callback():
1086+
raise ZeroDivisionError
1087+
root.tk.createcommand('callback', callback)
1088+
root.tk.call('after', 0, 'callback')
1089+
root.update()
1090+
# Let the mainloop() in other thread run for a while.
1091+
time.sleep(0.2)
1092+
# The error was not raised in other thread...
1093+
self.assertEqual(self.results, [('b', None)])
1094+
# ...but by the next mainloop() in this thread.
1095+
root.after(100, root.quit)
1096+
with self.assertRaises(ZeroDivisionError):
1097+
root.mainloop()
1098+
1099+
10081100
class TkTest(AbstractTkTest, unittest.TestCase):
10091101

10101102
def test_readprofile(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_unicodeobject.h" // _PyUnicode_AsUTF8String
3536

3637
#include <signal.h> // SIGINT
@@ -382,6 +383,7 @@ typedef struct {
382383
int threaded; /* True if tcl_platform[threaded] */
383384
Tcl_ThreadId thread_id;
384385
int dispatching;
386+
int quitting; /* Set by quit() to stop mainloop() */
385387
int event_hook; /* True if counted by EnableEventHook() */
386388
PyObject *trace;
387389
/* We cannot include tclInt.h, as this is internal.
@@ -433,9 +435,14 @@ check_tcl_appartment(TkappObject *app)
433435
/**** Error Handling ****/
434436

435437
static PyObject *Tkinter_TclError;
436-
static int quitMainLoop = 0;
437-
static int errorInCmd = 0;
438-
static PyObject *excInCmd;
438+
439+
/* An exception raised in a Python callback, which should be raised by the
440+
event loop (mainloop() or the event hook) that called the callback.
441+
Callbacks are only called in the thread of their Tcl interpreter, so it
442+
is thread-local. */
443+
static Tcl_ThreadDataKey excInCmd_key;
444+
#define excInCmd \
445+
(*(PyObject **)Tcl_GetThreadData(&excInCmd_key, sizeof(PyObject *)))
439446

440447

441448
static PyObject *Tkapp_UnicodeResult(TkappObject *);
@@ -2664,8 +2671,7 @@ PythonCmd(ClientData clientData, Tcl_Interp *interp,
26642671
goto done;
26652672

26662673
error:
2667-
errorInCmd = 1;
2668-
excInCmd = PyErr_GetRaisedException();
2674+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
26692675
done:
26702676
LEAVE_PYTHON
26712677

@@ -2903,8 +2909,7 @@ FileHandler(ClientData clientData, int mask)
29032909

29042910
res = PyObject_CallFunction(func, "Oi", file, mask);
29052911
if (res == NULL) {
2906-
errorInCmd = 1;
2907-
excInCmd = PyErr_GetRaisedException();
2912+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
29082913
}
29092914
Py_XDECREF(res);
29102915
LEAVE_PYTHON
@@ -3108,8 +3113,7 @@ TimerHandler(ClientData clientData)
31083113
Py_DECREF(v); /* See Tktt_New() */
31093114

31103115
if (res == NULL) {
3111-
errorInCmd = 1;
3112-
excInCmd = PyErr_GetRaisedException();
3116+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
31133117
}
31143118
else
31153119
Py_DECREF(res);
@@ -3174,10 +3178,10 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold)
31743178
int dispatching = self->dispatching;
31753179
self->dispatching = 1;
31763180

3177-
quitMainLoop = 0;
3181+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 0);
31783182
while (Tk_GetNumMainWindows() > threshold &&
3179-
!quitMainLoop &&
3180-
!errorInCmd)
3183+
!FT_ATOMIC_LOAD_INT_RELAXED(self->quitting) &&
3184+
excInCmd == NULL)
31813185
{
31823186
int result;
31833187

@@ -3207,12 +3211,12 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold)
32073211
break;
32083212
}
32093213
self->dispatching = dispatching;
3210-
quitMainLoop = 0;
3214+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 0);
32113215

3212-
if (errorInCmd) {
3213-
errorInCmd = 0;
3214-
PyErr_SetRaisedException(excInCmd);
3216+
PyObject *exc = excInCmd;
3217+
if (exc != NULL) {
32153218
excInCmd = NULL;
3219+
PyErr_SetRaisedException(exc);
32163220
return NULL;
32173221
}
32183222
Py_RETURN_NONE;
@@ -3238,6 +3242,13 @@ _tkinter_tkapp_dooneevent_impl(TkappObject *self, int flags)
32383242
return PyLong_FromLong(rv);
32393243
}
32403244

3245+
static int
3246+
QuitEventProc(Tcl_Event *evPtr, int flags)
3247+
{
3248+
/* Nothing to do: the event only wakes up the event loop. */
3249+
return 1;
3250+
}
3251+
32413252
/*[clinic input]
32423253
_tkinter.tkapp.quit
32433254
[clinic start generated code]*/
@@ -3246,7 +3257,21 @@ static PyObject *
32463257
_tkinter_tkapp_quit_impl(TkappObject *self)
32473258
/*[clinic end generated code: output=7f21eeff481f754f input=e03020dc38aff23c]*/
32483259
{
3249-
quitMainLoop = 1;
3260+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 1);
3261+
if (self->threaded && self->dispatching &&
3262+
self->thread_id != Tcl_GetCurrentThread())
3263+
{
3264+
/* mainloop() is running in other thread and can wait for an event.
3265+
Send it an event, so that it checks the flag. */
3266+
Tcl_Event *ev = (Tcl_Event *)attemptckalloc(sizeof(Tcl_Event));
3267+
if (ev == NULL) {
3268+
return PyErr_NoMemory();
3269+
}
3270+
memset(ev, 0, sizeof(Tcl_Event));
3271+
ev->proc = QuitEventProc;
3272+
Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL);
3273+
Tcl_ThreadAlert(self->thread_id);
3274+
}
32503275
Py_RETURN_NONE;
32513276
}
32523277

@@ -3774,7 +3799,6 @@ EventHook(void)
37743799
stdin_ready = 0;
37753800
#endif
37763801
PyEval_RestoreThread(tstate);
3777-
errorInCmd = 0;
37783802
#ifdef MS_WINDOWS
37793803
hStdin = GetStdHandle(STD_INPUT_HANDLE);
37803804
type = GetFileType(hStdin);
@@ -3832,10 +3856,10 @@ EventHook(void)
38323856
instead of returning to the prompt: without readline there is no
38333857
input waiting on stdin yet, so returning here would block in fgets
38343858
until the user hits enter, freezing later callbacks. */
3835-
if (errorInCmd) {
3836-
errorInCmd = 0;
3837-
PyErr_SetRaisedException(excInCmd);
3859+
PyObject *exc = excInCmd;
3860+
if (exc != NULL) {
38383861
excInCmd = NULL;
3862+
PyErr_SetRaisedException(exc);
38393863
PyErr_Print();
38403864
}
38413865
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
@@ -396,9 +396,6 @@ Modules/xxmodule.c - ErrorObject -
396396
## state
397397
Modules/_datetimemodule.c - _datetime_global_state -
398398
Modules/_tkinter.c - tcl_lock -
399-
Modules/_tkinter.c - excInCmd -
400-
Modules/_tkinter.c - valInCmd -
401-
Modules/_tkinter.c - trbInCmd -
402399
Modules/socketmodule.c - netdb_lock -
403400

404401

@@ -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
@@ -263,6 +263,7 @@ Modules/_struct.c - bigendian_table -
263263
Modules/_struct.c - lilendian_table -
264264
Modules/_struct.c - native_table -
265265
Modules/_tkinter.c - state_key -
266+
Modules/_tkinter.c - excInCmd_key -
266267
Modules/_interpchannelsmodule.c - _channelid_end_recv -
267268
Modules/_interpchannelsmodule.c - _channelid_end_send -
268269
Modules/_zoneinfo.c - DAYS_BEFORE_MONTH -

0 commit comments

Comments
 (0)