Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Make itertools.combinations_with_replacement thread-safe
  • Loading branch information
eendebakpt committed Feb 2, 2026
commit 56b615eacedbba719e688877e9ea3df0e0a86137
28 changes: 27 additions & 1 deletion Lib/test/test_free_threading/test_itertools.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import unittest
from threading import Thread, Barrier
from itertools import batched, chain, cycle
from itertools import batched, chain, combinations_with_replacement, cycle
from test.support import threading_helper


Expand Down Expand Up @@ -89,6 +89,32 @@ def work(it):

barrier.reset()

@threading_helper.reap_threads
def test_combinations_with_replacement(self):
number_of_threads = 6
number_of_iterations = 100
data = tuple(range(3))

barrier = Barrier(number_of_threads)
def work(it):
barrier.wait()
while True:
try:
v = next(it)
except StopIteration:
break

for _ in range(number_of_iterations):
cwr_iterator = combinations_with_replacement(data, 2)
worker_threads = []
for _ in range(number_of_threads):
worker_threads.append(
Thread(target=work, args=[cwr_iterator]))

with threading_helper.start_threads(worker_threads):
pass

barrier.reset()


if __name__ == "__main__":
Expand Down
12 changes: 11 additions & 1 deletion Modules/itertoolsmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2587,7 +2587,7 @@ cwr_traverse(PyObject *op, visitproc visit, void *arg)
}

static PyObject *
cwr_next(PyObject *op)
cwr_next_lock_held(PyObject *op)
{
cwrobject *co = cwrobject_CAST(op);
PyObject *elem;
Expand Down Expand Up @@ -2666,6 +2666,16 @@ cwr_next(PyObject *op)
return NULL;
}

static PyObject *
cwr_next(PyObject *op)
{
PyObject *result;
Py_BEGIN_CRITICAL_SECTION(op);
result = cwr_next_lock_held(op);
Py_END_CRITICAL_SECTION()
return result;
}

static PyMethodDef cwr_methods[] = {
{"__sizeof__", cwr_sizeof, METH_NOARGS, sizeof_doc},
{NULL, NULL} /* sentinel */
Expand Down