Skip to content

Commit cfd15b2

Browse files
miss-islingtonserhiy-storchakaclaude
authored
[3.15] gh-162647: Fix tkinter mainloop() with Tcl interpreters in different threads (GH-162649) (GH-162684)
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: Serhiy Storchaka <storchaka@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 541cbc9 commit cfd15b2

5 files changed

Lines changed: 144 additions & 26 deletions

File tree

‎Lib/test/test_tkinter/test_misc.py‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,17 @@
66
import sys
77
import textwrap
88
import threading
9+
import time
910
import unittest
1011
import weakref
12+
import _tkinter
1113
import tkinter
1214
from tkinter import TclError
1315
import enum
1416
from test import support
1517
from test.support import import_helper
1618
from test.support import os_helper
19+
from test.support import threading_helper
1720
from test.support.isolation import runInSubprocess
1821
from test.support.script_helper import assert_python_ok
1922
from test.test_tkinter.support import setUpModule # noqa: F401
@@ -829,6 +832,97 @@ def test_iterable_protocol(self):
829832
widget in widget
830833

831834

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

834928
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.
@@ -424,9 +426,14 @@ check_tcl_appartment(TkappObject *app)
424426
/**** Error Handling ****/
425427

426428
static PyObject *Tkinter_TclError;
427-
static int quitMainLoop = 0;
428-
static int errorInCmd = 0;
429-
static PyObject *excInCmd;
429+
430+
/* An exception raised in a Python callback, which should be raised by the
431+
event loop (mainloop() or the event hook) that called the callback.
432+
Callbacks are only called in the thread of their Tcl interpreter, so it
433+
is thread-local. */
434+
static Tcl_ThreadDataKey excInCmd_key;
435+
#define excInCmd \
436+
(*(PyObject **)Tcl_GetThreadData(&excInCmd_key, sizeof(PyObject *)))
430437

431438

432439
static PyObject *Tkapp_UnicodeResult(TkappObject *);
@@ -2526,8 +2533,7 @@ PythonCmd(ClientData clientData, Tcl_Interp *interp,
25262533
goto done;
25272534

25282535
error:
2529-
errorInCmd = 1;
2530-
excInCmd = PyErr_GetRaisedException();
2536+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
25312537
done:
25322538
LEAVE_PYTHON
25332539

@@ -2765,8 +2771,7 @@ FileHandler(ClientData clientData, int mask)
27652771

27662772
res = PyObject_CallFunction(func, "Oi", file, mask);
27672773
if (res == NULL) {
2768-
errorInCmd = 1;
2769-
excInCmd = PyErr_GetRaisedException();
2774+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
27702775
}
27712776
Py_XDECREF(res);
27722777
LEAVE_PYTHON
@@ -2944,8 +2949,7 @@ TimerHandler(ClientData clientData)
29442949
Py_DECREF(v); /* See Tktt_New() */
29452950

29462951
if (res == NULL) {
2947-
errorInCmd = 1;
2948-
excInCmd = PyErr_GetRaisedException();
2952+
Py_XSETREF(excInCmd, PyErr_GetRaisedException());
29492953
}
29502954
else
29512955
Py_DECREF(res);
@@ -3010,10 +3014,10 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold)
30103014
int dispatching = self->dispatching;
30113015
self->dispatching = 1;
30123016

3013-
quitMainLoop = 0;
3017+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 0);
30143018
while (Tk_GetNumMainWindows() > threshold &&
3015-
!quitMainLoop &&
3016-
!errorInCmd)
3019+
!FT_ATOMIC_LOAD_INT_RELAXED(self->quitting) &&
3020+
excInCmd == NULL)
30173021
{
30183022
int result;
30193023

@@ -3043,12 +3047,12 @@ _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold)
30433047
break;
30443048
}
30453049
self->dispatching = dispatching;
3046-
quitMainLoop = 0;
3050+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 0);
30473051

3048-
if (errorInCmd) {
3049-
errorInCmd = 0;
3050-
PyErr_SetRaisedException(excInCmd);
3052+
PyObject *exc = excInCmd;
3053+
if (exc != NULL) {
30513054
excInCmd = NULL;
3055+
PyErr_SetRaisedException(exc);
30523056
return NULL;
30533057
}
30543058
Py_RETURN_NONE;
@@ -3074,6 +3078,13 @@ _tkinter_tkapp_dooneevent_impl(TkappObject *self, int flags)
30743078
return PyLong_FromLong(rv);
30753079
}
30763080

3081+
static int
3082+
QuitEventProc(Tcl_Event *evPtr, int flags)
3083+
{
3084+
/* Nothing to do: the event only wakes up the event loop. */
3085+
return 1;
3086+
}
3087+
30773088
/*[clinic input]
30783089
_tkinter.tkapp.quit
30793090
[clinic start generated code]*/
@@ -3082,7 +3093,21 @@ static PyObject *
30823093
_tkinter_tkapp_quit_impl(TkappObject *self)
30833094
/*[clinic end generated code: output=7f21eeff481f754f input=e03020dc38aff23c]*/
30843095
{
3085-
quitMainLoop = 1;
3096+
FT_ATOMIC_STORE_INT_RELAXED(self->quitting, 1);
3097+
if (self->threaded && self->dispatching &&
3098+
self->thread_id != Tcl_GetCurrentThread())
3099+
{
3100+
/* mainloop() is running in other thread and can wait for an event.
3101+
Send it an event, so that it checks the flag. */
3102+
Tcl_Event *ev = (Tcl_Event *)attemptckalloc(sizeof(Tcl_Event));
3103+
if (ev == NULL) {
3104+
return PyErr_NoMemory();
3105+
}
3106+
memset(ev, 0, sizeof(Tcl_Event));
3107+
ev->proc = QuitEventProc;
3108+
Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL);
3109+
Tcl_ThreadAlert(self->thread_id);
3110+
}
30863111
Py_RETURN_NONE;
30873112
}
30883113

@@ -3579,7 +3604,6 @@ EventHook(void)
35793604
stdin_ready = 0;
35803605
#endif
35813606
PyEval_RestoreThread(tstate);
3582-
errorInCmd = 0;
35833607
#ifdef MS_WINDOWS
35843608
hStdin = GetStdHandle(STD_INPUT_HANDLE);
35853609
type = GetFileType(hStdin);
@@ -3637,10 +3661,10 @@ EventHook(void)
36373661
instead of returning to the prompt: without readline there is no
36383662
input waiting on stdin yet, so returning here would block in fgets
36393663
until the user hits enter, freezing later callbacks. */
3640-
if (errorInCmd) {
3641-
errorInCmd = 0;
3642-
PyErr_SetRaisedException(excInCmd);
3664+
PyObject *exc = excInCmd;
3665+
if (exc != NULL) {
36433666
excInCmd = NULL;
3667+
PyErr_SetRaisedException(exc);
36443668
PyErr_Print();
36453669
}
36463670
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
@@ -401,9 +401,6 @@ Modules/xxmodule.c - ErrorObject -
401401
## state
402402
Modules/_datetimemodule.c - _datetime_global_state -
403403
Modules/_tkinter.c - tcl_lock -
404-
Modules/_tkinter.c - excInCmd -
405-
Modules/_tkinter.c - valInCmd -
406-
Modules/_tkinter.c - trbInCmd -
407404
Modules/socketmodule.c - netdb_lock -
408405

409406

@@ -434,8 +431,6 @@ Modules/readline.c - libedit_history_start -
434431
Modules/_ctypes/malloc_closure.c - free_list -
435432
Modules/_curses_panel.c - lop -
436433
Modules/_ssl/debughelpers.c _PySSL_keylog_callback lock -
437-
Modules/_tkinter.c - quitMainLoop -
438-
Modules/_tkinter.c - errorInCmd -
439434
Modules/_tkinter.c - Tkinter_busywaitinterval -
440435
Modules/_tkinter.c - call_mutex -
441436
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)