57

我正在使用新concurrent.futures模块(它也有一个 Python 2 反向端口)来执行一些简单的多线程 I/O。我无法理解如何干净地杀死使用此模块开始的任务。

查看以下 Python 2/3 脚本,它重现了我看到的行为:

#!/usr/bin/env python
from __future__ import print_function

import concurrent.futures
import time


def control_c_this():
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        future1 = executor.submit(wait_a_bit, name="Jack")
        future2 = executor.submit(wait_a_bit, name="Jill")

        for future in concurrent.futures.as_completed([future1, future2]):
            future.result()

        print("All done!")


def wait_a_bit(name):
    print("{n} is waiting...".format(n=name))
    time.sleep(100)


if __name__ == "__main__":
    control_c_this()

在此脚本运行时,使用常规的 Control-C 键盘中断似乎无法彻底终止。我在 OS X 上运行。

  • 在 Python 2.7 上,我必须求助于kill命令行来终止脚本。Control-C 只是被忽略。
  • 在 Python 3.4 上,如果你按两次 Control-C 就可以工作,但随后会转储很多奇怪的堆栈跟踪。

我在网上找到的大多数文档都讨论了如何使用旧threading模块彻底杀死线程。它似乎都不适用于这里。

并且concurrent.futures模块中提供的所有停止东西的方法(如Executor.shutdown()and Future.cancel())仅在 Futures 尚未启动或完成时才起作用,在这种情况下这是没有意义的。我想立即打断未来。

我的用例很简单:当用户按下 Control-C 时,脚本应该像任何表现良好的脚本一样立即退出。这就是我想要的。

那么在使用时获得这种行为的正确方法是什么concurrent.futures

4

3 回答 3

38

这有点痛苦。本质上,您的工作线程必须在您的主线程退出之前完成。除非他们退出,否则您无法退出。典型的解决方法是拥有一些全局状态,每个线程都可以检查以确定它们是否应该做更多的工作。

这是解释原因的引文。本质上,如果线程在解释器退出时退出,则可能会发生不好的事情。

这是一个工作示例。请注意,由于子线程的睡眠持续时间,Cc 最多需要 1 秒才能传播。

#!/usr/bin/env python
from __future__ import print_function

import concurrent.futures
import time
import sys

quit = False
def wait_a_bit(name):
    while not quit:
        print("{n} is doing work...".format(n=name))
        time.sleep(1)

def setup():
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
    future1 = executor.submit(wait_a_bit, "Jack")
    future2 = executor.submit(wait_a_bit, "Jill")

    # main thread must be doing "work" to be able to catch a Ctrl+C 
    # http://www.luke.maurits.id.au/blog/post/threads-and-signals-in-python.html
    while (not (future1.done() and future2.done())):
        time.sleep(1)

if __name__ == "__main__":
    try:
        setup()
    except KeyboardInterrupt:
        quit = True
于 2015-03-24T15:58:33.417 回答
7

我遇到了这个问题,但我遇到的问题是许多期货(成千上万的)将等待运行,只需按下 Ctrl-C 就会让它们等待,而不是真正退出。我concurrent.futures.wait用来运行一个进度循环,需要添加一个try ... except KeyboardInterrupt来处理取消未完成的期货。

POLL_INTERVAL = 5
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
    futures = [pool.submit(do_work, arg) for arg in large_set_to_do_work_over]
    # next line returns instantly
    done, not_done = concurrent.futures.wait(futures, timeout=0)
    try:
        while not_done:
            # next line 'sleeps' this main thread, letting the thread pool run
            freshly_done, not_done = concurrent.futures.wait(not_done, timeout=POLL_INTERVAL)
            done |= freshly_done
            # more polling stats calculated here and printed every POLL_INTERVAL seconds...
    except KeyboardInterrupt:
        # only futures that are not done will prevent exiting
        for future in not_done:
            # cancel() returns False if it's already done or currently running,
            # and True if was able to cancel it; we don't need that return value
            _ = future.cancel()
         # wait for running futures that the above for loop couldn't cancel (note timeout)
         _ = concurrent.futures.wait(not_done, timeout=None)

如果您对准确跟踪已完成和未完成的内容感兴趣(即不想要进度循环),您可以将第一个等待调用(带有 的timeout=0)替换为not_done = futures并保留while not_done:逻辑。

取消循环可能会根据该for future in not_done:返回值表现不同(或写为理解),但等待完成或取消的期货并不是真正的等待——它会立即返回。最后一个waitwithtimeout=None确保池的运行作业确实完成。

同样,这只有在do_work实际调用的最终在合理的时间内返回时才能正常工作。这对我来说很好 - 事实上,我想确保如果do_work开始,它会运行到完成。如果do_work是“无止境”,那么您将需要类似 cdosborn 的答案,它使用对所有线程可见的变量,指示它们自行停止。

于 2020-08-19T21:36:14.417 回答
0

聚会迟到了,但我也遇到了同样的问题。

我想立即杀死我的程序,我不在乎发生了什么。除了 Linux 将做的事情之外,我不需要完全关闭。

我发现os.kill(os.getpid(), 9)在第一个 ^C 之后立即将 KeyboardInterrupt 异常处理程序中的 geitda 代码替换为退出。

于 2021-12-21T22:40:10.513 回答