【问题标题】:multithreading killing thread after timeout - python 2.7超时后多线程杀死线程 - python 2.7
【发布时间】:2016-07-10 16:38:34
【问题描述】:

我正在运行一个异步程序,我启动的每个线程,我都想要它

有一个超时,如果它没有完成功能,它会停止并杀死自己(或者其他一些线程会杀死它)

func(my_item, num1, num2, num3, timeout):
    calc = num1+num2
    # something that takes long time(on my_item)

for item in my_list:
        if item.bool:
            new_thread = threading.Thread(target=func, (item, 1, 2, 3, item.timeout))
            new_thread.start()

现在我希望主线程继续启动新线程,但我也希望每个线程都有一个超时时间,这样线程就不会永远继续下去。

我使用的是 Windows 而不是 UNIX,所以我无法运行 SINGLRM

谢谢!

【问题讨论】:

    标签: python multithreading time timeout


    【解决方案1】:

    杀死线程是一种不好的做法,长时间运行的函数最好检查状态标志并自行退出,而不是外部因素突然杀死线程。一个简单的检查,用 time.time() 记录函数调用的开始时间,并每隔一段时间进行比较,即:

    def func(x, y, timeout):
        start = time.time()
        while time.time() < (start + timeout):
            # Do stuff
    

    或者添加一个函数可以间隔调用的方法,当超过超时时间时会引发异常,您的长时间运行的函数可以在 try/except 块中捕获以清理并退出线程:

    def check_timeout(start_time, timeout):
        if time.time() > (start_time + timeout):
            raise TimeoutException
    
    try:
        # Stuff
        check_timeout(start_time, timeout)
        # Bit more stuff
        check_timeout(start_time, timeout)
        # Bit more stuff
        check_timeout(start_time, timeout)
        # Bit more stuff
        # All done!
        return "everything is awesome"
    
    except TimeoutException:
        # Cleanup and let thread end
    

    我会推荐这个帖子作为一个很好的阅读:Is there any way to kill a Thread in Python?

    【讨论】:

    • 这是个问题。因为我在我的 func 中运行了一个运行 cmd 命令的子进程,并且它本身需要很长时间。我可以及时限制子过程吗?
    • 所以你的 Python 代码正在从命令行执行另一个程序?
    • 这可能对你有帮助:stackoverflow.com/questions/16866602/…
    • 好的,我试试。谢谢!
    猜你喜欢
    • 2015-10-30
    • 2022-10-16
    • 2011-04-19
    • 1970-01-01
    • 2014-05-10
    • 2012-11-18
    • 1970-01-01
    • 2021-11-13
    • 2014-10-24
    相关资源
    最近更新 更多