gh-120496: Make enum_iter thread safe by eendebakpt · Pull Request #120591 · python/cpython · GitHub
Skip to content
Closed
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
3 changes: 3 additions & 0 deletions Include/internal/pycore_critical_section.h
28 changes: 28 additions & 0 deletions Lib/test/test_enumerate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import sys
import pickle
import gc
from threading import Thread

from test import support
from test.support import threading_helper

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


class EnumerateThreading(unittest.TestCase):
@staticmethod
def work(enum, start):
while True:
try:
value = next(enum)
except StopIteration:
break
else:
if value[0] + start != value[1]:
raise ValueError(f'enumerate returned pair {value}')

@threading_helper.reap_threads
@threading_helper.requires_working_threading()
def test_threading(self):
number_of_threads = 4
n = 100
start = sys.maxsize-10
enum = enumerate(range(start, start + n))
worker_threads = []
for ii in range(number_of_threads):
worker_threads.append(Thread(target=self.work, args=[enum, start]))
_ = [t.start() for t in worker_threads]
_ = [t.join() for t in worker_threads]


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make :class:`enumerate` thread-safe.
26 changes: 21 additions & 5 deletions Objects/enumobject.c