Skip to content
Draft
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
4 changes: 3 additions & 1 deletion Doc/library/decimal.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions Lib/_pydecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
55 changes: 55 additions & 0 deletions Lib/test/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
24 changes: 21 additions & 3 deletions Lib/threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions Modules/_decimal/_decimal.c
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down
Loading