请参阅下面的代码片段,它无法通过Python 3.10在本地的第一次运行。
当我试图
join
内置线程中的所有线程
all
函数中,始终有一个线程仍处于活动状态。
这里的问题是什么,为什么会出现种族状况?
import time
from threading import Thread
def expose_race_condition(run_index: int) -> None:
threads: list[Thread] = [
Thread(target=time.sleep, args=(1,)) for _ in range(10)
]
for thread in threads:
thread.start()
# RACE CONDITION IS HERE
assert not all(thread.join() for thread in threads)
for thread_index, thread in enumerate(threads):
# Uncommenting the below line defeats the race condition
# assert not thread.join()
assert (
not thread.is_alive()
), f"Worker {thread_index} in run {run_index} was still alive."
print(f"Completed run {run_index}")
if __name__ == "__main__":
for i in range(10_000):
expose_race_condition(i)