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
28 changes: 28 additions & 0 deletions Lib/test/test_itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2489,6 +2489,34 @@ def __eq__(self, other):
for j in range(2):
next(g, None) # shouldn't crash

@threading_helper.requires_working_threading()
def test_islice_thread_safety(self):
# gh-151409: islice must not yield more items than its stop argument
# when consumed concurrently from multiple threads.
STOP = 100
NTHREADS = 8
data = iter(range(STOP + NTHREADS * 2))
sl = islice(data, STOP)
results: list[int] = []
lock = threading.Lock()

def consume() -> None:
while True:
v = next(sl, None)
if v is None:
break
with lock:
results.append(v)

threads = [threading.Thread(target=consume) for _ in range(NTHREADS)]
for t in threads:
t.start()
for t in threads:
t.join()

self.assertLessEqual(len(results), STOP)
self.assertEqual(sorted(results), list(range(len(results))))


class SubclassWithKwargsTest(unittest.TestCase):
def test_keywords_in_subclass(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :class:`itertools.islice` to be thread-safe when shared across threads.
14 changes: 12 additions & 2 deletions Modules/itertoolsmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1625,8 +1625,8 @@ islice_traverse(PyObject *op, visitproc visit, void *arg)
return 0;
}

static PyObject *
islice_next(PyObject *op)
static inline PyObject *
islice_next_lock_held(PyObject *op)
{
isliceobject *lz = isliceobject_CAST(op);
PyObject *item;
Expand Down Expand Up @@ -1665,6 +1665,16 @@ islice_next(PyObject *op)
return NULL;
}

static PyObject *
islice_next(PyObject *op)
{
PyObject *result;
Py_BEGIN_CRITICAL_SECTION(op);
result = islice_next_lock_held(op);
Py_END_CRITICAL_SECTION();
return result;
}

PyDoc_STRVAR(islice_doc,
"islice(iterable, stop) --> islice object\n\
islice(iterable, start, stop[, step]) --> islice object\n\
Expand Down
Loading