Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions Lib/test/test_tcl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
import subprocess
import sys
import os
import threading
from test import support
from test.support import import_helper
from test.support import os_helper
from test.support import threading_helper
from test.support.isolation import runInSubprocess

# Skip this test if the _tkinter module wasn't built.
_tkinter = import_helper.import_module('_tkinter')
Expand Down Expand Up @@ -33,6 +36,29 @@ def testFlattenLen(self):
self.assertRaises(TypeError, _tkinter._flatten, 'string')
self.assertRaises(TypeError, _tkinter._flatten, {'set'})

@unittest.skipUnless(support.Py_GIL_DISABLED,
'requires the free-threaded build')
@threading_helper.requires_working_threading()
@runInSubprocess()
def test_create_concurrent(self):
# gh-154923: Create Tcl interpreters in different threads at once.
# Run in a fresh process, where no interpreter was created yet.
nthreads = 16
start = threading.Barrier(nthreads)
errors = []
def worker():
try:
start.wait()
for _ in range(8):
_tkinter.create(None, '', 'Tk', False, 1, False, False,
None)
except Exception as e:
errors.append(e)
threads = [threading.Thread(target=worker) for _ in range(nthreads)]
with threading_helper.start_threads(threads):
pass
self.assertEqual(errors, [])


class TclTest(unittest.TestCase):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a crash when creating Tcl interpreters concurrently in different
threads in the :term:`free-threaded build`.
7 changes: 7 additions & 0 deletions Modules/_tkinter.c
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,11 @@ Tkapp_New(const char *screenName, const char *className,
if (v == NULL)
return NULL;

/* Without the GIL, two threads could both free tcl_lock below, and
the first-time initialization in Tcl_CreateInterp() is not
thread-safe either. Serialize them. */
static PyMutex tcl_create_mutex;
PyMutex_Lock(&tcl_create_mutex);
v->interp = Tcl_CreateInterp();
v->wantobjects = wantobjects;
#if TCL_MAJOR_VERSION >= 9
Expand All @@ -685,6 +690,7 @@ Tkapp_New(const char *screenName, const char *className,

#ifndef TCL_THREADS
if (v->threaded) {
PyMutex_Unlock(&tcl_create_mutex);
PyErr_SetString(PyExc_RuntimeError,
"Tcl is threaded but _tkinter is not");
Py_DECREF(v);
Expand All @@ -696,6 +702,7 @@ Tkapp_New(const char *screenName, const char *className,
PyThread_free_lock(tcl_lock);
tcl_lock = NULL;
}
PyMutex_Unlock(&tcl_create_mutex);

v->OldBooleanType = Tcl_GetObjType("boolean");
{
Expand Down
Loading