From fd9519f70e0867dabceab77b9cc10bdd828bf13f Mon Sep 17 00:00:00 2001 From: Neil Schemenauer Date: Mon, 16 Nov 2026 11:23:55 -0700 Subject: [PATCH] gh-141148: Copy decimal context for threads that inherit context When sys.flags.thread_inherit_context is true, have Thread.start() replace the decimal context in the new thread's context with a copy (with flags cleared). --- Doc/library/decimal.rst | 4 +- Lib/_pydecimal.py | 2 + Lib/test/test_decimal.py | 55 +++++++++++++++++++ Lib/threading.py | 24 +++++++- ...-11-16-12-00-00.gh-issue-141148.dCtxTh.rst | 5 ++ Modules/_decimal/_decimal.c | 4 ++ 6 files changed, 90 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-16-12-00-00.gh-issue-141148.dCtxTh.rst diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst index 93eac9083f29ddb..ab55c7ce4c1696d 100644 --- a/Doc/library/decimal.rst +++ b/Doc/library/decimal.rst @@ -1986,7 +1986,9 @@ new threads. If the flag is false, new threads will start with an empty context. In this case, :func:`getcontext` will create a new context object when called and use the default values from *DefaultContext*. If the flag is true, new threads will start with a copy of context from the caller of -:meth:`threading.Thread.start`. +:meth:`threading.Thread.start`. The copy has the same settings as the +context of the caller but its flags are cleared, and changes made to it are +not seen by other threads. To control the defaults so that each thread will use the same values throughout the application, directly modify the *DefaultContext* object. This should be diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py index 4b7bfd07887bd38..884ad6bf608ebb2 100644 --- a/Lib/_pydecimal.py +++ b/Lib/_pydecimal.py @@ -349,6 +349,8 @@ class FloatOperation(DecimalException, TypeError): import contextvars +# Also used by threading.Thread.start() to give a thread that inherits the +# context of its caller a separate decimal context. _current_context_var = contextvars.ContextVar('decimal_context') _context_attributes = frozenset( diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index ef7aa5358b5cc64..5c8ac554a4f494e 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -41,9 +41,11 @@ run_with_locale, cpython_only, darwin_malloc_err_warning) from test.support.import_helper import import_fresh_module +from test.support.script_helper import assert_python_ok from test.support import threading_helper from test.support import warnings_helper import random +import textwrap import inspect import threading import contextvars @@ -1772,6 +1774,59 @@ def test_threading(self): DefaultContext.Emax = save_emax DefaultContext.Emin = save_emin + def test_thread_inherit_context(self): + # gh-141148: a thread that inherits the context of the caller of + # Thread.start() must get its own copy of the decimal context. + code = textwrap.dedent(""" + import sys + import threading + if sys.argv[1] == 'P': + sys.modules['_decimal'] = None + import decimal + from decimal import getcontext, Decimal, Inexact + + assert sys.flags.thread_inherit_context + + def child(): + ctx = getcontext() + result.append((ctx is parent, ctx.prec, ctx.Emax, + ctx.traps[Inexact], ctx.flags[Inexact])) + ctx.prec = 5 + ctx.traps[Inexact] = False + Decimal(1) / Decimal(3) + result.append(ctx.flags[Inexact]) + + def run_thread(): + t = threading.Thread(target=child) + t.start() + t.join() + + # The caller has no decimal context yet. + result = [] + parent = None + run_thread() + assert result == [(False, 28, 999999, False, False), True], result + + parent = getcontext() + parent.prec = 40 + parent.Emax = 1000 + Decimal(1) / Decimal(3) + parent.traps[Inexact] = True + assert parent.flags[Inexact] + parent.clear_flags() + parent.flags[Inexact] = True + + result = [] + run_thread() + assert result == [(False, 40, 1000, True, False), True], result + + assert getcontext() is parent + assert parent.prec == 40 + assert parent.traps[Inexact] + """) + which = 'C' if self.decimal == C else 'P' + assert_python_ok('-X', 'thread_inherit_context=1', '-c', code, which) + @requires_cdecimal class CThreadingTest(ThreadingTest, unittest.TestCase): diff --git a/Lib/threading.py b/Lib/threading.py index 507d40a1baa275f..1b8de6f3b47c9d7 100644 --- a/Lib/threading.py +++ b/Lib/threading.py @@ -986,6 +986,23 @@ def __next__(self): ############################################################ +def _copy_decimal_context(context): + # Copying a contextvars.Context is shallow, so a thread that inherits the + # context of its caller would share the caller's mutable decimal.Context + # object. Give the new thread its own copy, so that changes it makes + # with decimal.getcontext() are not seen by other threads. If the caller + # has no decimal context yet, there is nothing to share. + for name in ('_decimal', '_pydecimal'): + var = getattr(_sys.modules.get(name), '_current_context_var', None) + if var is None: + continue + decimal_context = context.get(var) + if decimal_context is not None: + decimal_context = decimal_context.copy() + decimal_context.clear_flags() + context.run(var.set, decimal_context) + + # Helper to generate new thread names _counter = _count(1).__next__ def _newname(name_template): @@ -1125,18 +1142,19 @@ def start(self): if self._started.is_set(): raise RuntimeError("threads can only be started once") - with _active_limbo_lock: - _limbo[self] = self - if self._context is None: # No context provided if _sys.flags.thread_inherit_context: # start with a copy of the context of the caller self._context = _contextvars.copy_context() + _copy_decimal_context(self._context) else: # start with an empty context self._context = _contextvars.Context() + with _active_limbo_lock: + _limbo[self] = self + try: # Start joinable thread _start_joinable_thread(self._bootstrap, handle=self._os_thread_handle, diff --git a/Misc/NEWS.d/next/Library/2026-11-16-12-00-00.gh-issue-141148.dCtxTh.rst b/Misc/NEWS.d/next/Library/2026-11-16-12-00-00.gh-issue-141148.dCtxTh.rst new file mode 100644 index 000000000000000..642dc9adb1e3ef5 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-16-12-00-00.gh-issue-141148.dCtxTh.rst @@ -0,0 +1,5 @@ +When :data:`sys.flags.thread_inherit_context` is true, a thread started with +:meth:`threading.Thread.start` now gets its own copy of the :mod:`decimal` +context of the caller instead of sharing the same context object. Previously, +changes made with :func:`decimal.getcontext` in one thread were seen by the +other threads. diff --git a/Modules/_decimal/_decimal.c b/Modules/_decimal/_decimal.c index 3a128a13222f9b5..760096425a357dd 100644 --- a/Modules/_decimal/_decimal.c +++ b/Modules/_decimal/_decimal.c @@ -8077,6 +8077,10 @@ _decimal_exec(PyObject *m) #else ASSIGN_PTR(state->current_context_var, PyContextVar_New("decimal_context", NULL)); CHECK_INT(PyModule_AddObjectRef(m, "HAVE_CONTEXTVAR", Py_True)); + /* Private, used by threading.Thread.start() to give a thread that + inherits the context of its caller a separate decimal context. */ + CHECK_INT(PyModule_AddObjectRef(m, "_current_context_var", + state->current_context_var)); #endif CHECK_INT(PyModule_AddObjectRef(m, "HAVE_THREADS", Py_True));