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
1 change: 1 addition & 0 deletions Lib/test/libregrtest/tsan.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'test_ctypes',
# 'test_concurrent_futures', # gh-130605: too many data races
'test_enum',
'test_enumerate',
'test_functools',
'test_httpservers',
'test_imaplib',
Expand Down
26 changes: 26 additions & 0 deletions Lib/test/test_enumerate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
import sys
import pickle
import gc
import threading


from test import support
from test.support import threading_helper

class G:
'Sequence using __getitem__'
Expand Down Expand Up @@ -292,5 +295,28 @@ def enum(self, iterable, start=sys.maxsize + 1):
(sys.maxsize+3,'c')]


@threading_helper.requires_working_threading()
class TestThreadSafety(EnumerateStartTestCase):
def test_thread_safety_while_iterating(self):
# gh-153932: calling reduce while iterating should pass with TSAN

en = enumerate(range(10_000))
stop = threading.Event()

def advance():
for _ in en:
pass
stop.set()

def read():
while not stop.is_set():
en.__reduce__()

threads = [threading.Thread(target=advance), threading.Thread(target=read)]

with threading_helper.start_threads(threads):
pass


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix thread safety issue in the ``__reduce__`` method of
:py:class:`enumerate`.
9 changes: 6 additions & 3 deletions Objects/enumobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,13 @@ enum_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
enumobject *en = _enumobject_CAST(op);
PyObject *result;
Py_BEGIN_CRITICAL_SECTION(en);
if (en->en_longindex != NULL)
if (en->en_longindex != NULL) {
result = Py_BuildValue("O(OO)", Py_TYPE(en), en->en_sit, en->en_longindex);
else
result = Py_BuildValue("O(On)", Py_TYPE(en), en->en_sit, en->en_index);
}
else {
Py_ssize_t en_index = FT_ATOMIC_LOAD_SSIZE_RELAXED(en->en_index);
result = Py_BuildValue("O(On)", Py_TYPE(en), en->en_sit, en_index);
}
Py_END_CRITICAL_SECTION();
return result;
}
Expand Down
Loading