@@ -314,31 +314,41 @@ def test_tier2_invalidates_iterator(self):
314314 @support .requires_resource ("cpu" )
315315 def test_list_init_thread_safety (self ):
316316 # GH-126369: list.__init__() didn't lock iterables
317- from threading import Thread
317+ from threading import Thread , Lock
318+ import contextlib
318319
319320 def my_generator ():
320321 for i in range (100000 ):
321322 yield i
322323
324+
325+ lock = Lock ()
326+ amount = 0
327+ thread_count = 10
328+
323329 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 )]
330+ # Note: it's intentional to throw out the exception here. Generators
331+ # aren't thread safe, so who knows what will happen. Right now, it just spams
332+ # a lot of ValueError's, but that might change if we decide to make generators
333+ # thread safe in the future. We're just making sure it doesn't crash.
334+ with contextlib .suppress (ValueError ):
335+ list (gen )
336+
337+ with lock :
338+ nonlocal amount
339+ amount += 1
340+
341+ with threading_helper .catch_threading_exception () as cm :
342+ ts = [Thread (target = gen_to_list , args = (my_generator (),)) for _ in range (thread_count )]
333343 for t in ts :
334344 t .start ()
335345
336346 for t in ts :
337347 t .join ()
338348
339- # Make sure it exhausted the generator
340- with self . assertRaises ( StopIteration ):
341- next ( target )
349+ self . assertIsNone ( cm . exc_value )
350+
351+ self . assertEqual ( amount , thread_count )
342352
343353
344354if __name__ == "__main__" :
0 commit comments