Skip to content

Commit 1b65c9c

Browse files
test: add regression test
1 parent c82bf62 commit 1b65c9c

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lib/test/test_itertools.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2489,6 +2489,34 @@ def __eq__(self, other):
24892489
for j in range(2):
24902490
next(g, None) # shouldn't crash
24912491

2492+
@threading_helper.requires_working_threading()
2493+
def test_islice_thread_safety(self):
2494+
# gh-151409: islice must not yield more items than its stop argument
2495+
# when consumed concurrently from multiple threads.
2496+
STOP = 100
2497+
NTHREADS = 8
2498+
data = iter(range(STOP + NTHREADS * 2))
2499+
sl = islice(data, STOP)
2500+
results: list[int] = []
2501+
lock = threading.Lock()
2502+
2503+
def consume() -> None:
2504+
while True:
2505+
v = next(sl, None)
2506+
if v is None:
2507+
break
2508+
with lock:
2509+
results.append(v)
2510+
2511+
threads = [threading.Thread(target=consume) for _ in range(NTHREADS)]
2512+
for t in threads:
2513+
t.start()
2514+
for t in threads:
2515+
t.join()
2516+
2517+
self.assertLessEqual(len(results), STOP)
2518+
self.assertEqual(sorted(results), list(range(len(results))))
2519+
24922520

24932521
class SubclassWithKwargsTest(unittest.TestCase):
24942522
def test_keywords_in_subclass(self):

0 commit comments

Comments
 (0)