Py学习  »  Python

通过all函数连接线程的Python竞赛条件

Intrastellar Explorer • 3 年前 • 1111 次点击  

请参阅下面的代码片段,它无法通过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)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132705
 
1111 次点击  
文章 [ 1 ]  |  最新文章 3 年前