File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 11import sys
22from test import list_tests
3+ from test import support
4+ from test .support import threading_helper
35from test .support import cpython_only
46import pickle
57import unittest
@@ -309,5 +311,35 @@ def test_tier2_invalidates_iterator(self):
309311 a .append (4 )
310312 self .assertEqual (list (it ), [])
311313
314+ @support .requires_resource ("cpu" )
315+ def test_list_init_thread_safety (self ):
316+ # GH-126369: list.__init__() didn't lock iterables
317+ from threading import Thread
318+
319+ def my_generator ():
320+ for i in range (100000 ):
321+ yield i
322+
323+ def gen_to_list (gen ):
324+ list (gen )
325+
326+ target = my_generator ()
327+ # Note: it's intentional to throw out the exception here. Generators
328+ # aren't thread safe, so who knows what will happen. Right now, it just spams
329+ # a lot of ValueError's, but that might change if we decide to make generators
330+ # thread safe in the future. We're just making sure it doesn't crash.
331+ with threading_helper .catch_threading_exception ():
332+ ts = [Thread (target = gen_to_list , args = (my_generator (),)) for _ in range (10 )]
333+ for t in ts :
334+ t .start ()
335+
336+ for t in ts :
337+ t .join ()
338+
339+ # Make sure it exhausted the generator
340+ with self .assertRaises (StopIteration ):
341+ next (target )
342+
343+
312344if __name__ == "__main__" :
313345 unittest .main ()
You can’t perform that action at this time.
0 commit comments