Skip to content
Open
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
25 changes: 24 additions & 1 deletion Lib/test/test_free_threading/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from ast import Or
from functools import partial
from threading import Barrier, Thread
from threading import Barrier, Event, Thread
from unittest import TestCase

try:
Expand Down Expand Up @@ -356,5 +356,28 @@ def writer():

threading_helper.run_concurrently([reader, writer])

def test_racing_update_from_mutating_pair(self):
# gh-159244: dict() must not read the items of a key/value pair
# that another thread empties concurrently.
pair = [object(), object()]
done = Event()

def writer():
try:
for _ in range(10000):
pair.clear()
pair.extend((object(), object()))
finally:
done.set()

def reader():
while not done.is_set():
try:
dict([pair])
except ValueError:
pass

threading_helper.run_concurrently([writer] + [reader] * 4)

if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a crash in :class:`dict` and :meth:`dict.update` in the
:term:`free-threaded build` when another thread concurrently mutates a list
used as a key/value pair. Patch by Christian Aurich Zanettini Martins.
12 changes: 7 additions & 5 deletions Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -4115,7 +4115,7 @@ merge_from_seq2_lock_held(PyObject *d, PyObject *seq2, int override)
return -1;

for (i = 0; ; ++i) {
PyObject *key, *value;
PyObject *key = NULL, *value = NULL;
Py_ssize_t n;

fast = NULL;
Expand All @@ -4137,7 +4137,13 @@ merge_from_seq2_lock_held(PyObject *d, PyObject *seq2, int override)
}
goto Fail;
}
Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(item);
n = PySequence_Fast_GET_SIZE(fast);
if (n == 2) {
key = Py_NewRef(PySequence_Fast_GET_ITEM(fast, 0));
value = Py_NewRef(PySequence_Fast_GET_ITEM(fast, 1));
}
Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
if (n != 2) {
PyErr_Format(PyExc_ValueError,
"dictionary update sequence element #%zd "
Expand All @@ -4147,10 +4153,6 @@ merge_from_seq2_lock_held(PyObject *d, PyObject *seq2, int override)
}

/* Update/merge with this (key, value) pair. */
key = PySequence_Fast_GET_ITEM(fast, 0);
value = PySequence_Fast_GET_ITEM(fast, 1);
Py_INCREF(key);
Py_INCREF(value);
if (override) {
if (setitem_lock_held((PyDictObject *)d, key, value) < 0) {
Py_DECREF(key);
Expand Down
Loading