社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Intrastellar Explorer • 3 年前 • 1015 次点击  

请参阅下面的代码片段,它无法通过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
 
1015 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Tim Peters
Reply   •   1 楼
Tim Peters    3 年前

对不起,我不明白你想做什么。例如,这一行:

   assert not all(thread.join() for thread in threads)

这根本没道理。 .join() 总是 返回 None ,所以和

   assert not all(None for thread in threads)

除了它有连接螺纹的副作用。 all() 第一次看到故障时短路 False 价值,哪个 没有一个 是的,所以只有第一个 .加入 实际上叫。 all(...) 返回 错误的 所以 not all(...) 返回 True ,所以 assert 成功了。就像:

    threads[0].join()
    assert True

短期课程: 任何 代码是否关注值 thread.join() 回报很可能是断断续续的,因为 没有一个 是它唯一能看到的价值。