【问题标题】:Keyboardinterrupt doesn't stop threading to keep on going in pythonKeyboardinterrupt 不会停止线程以继续在 python 中运行
【发布时间】:2021-01-15 22:52:03
【问题描述】:

这段代码运行良好,我唯一的问题是当我需要停止我的代码时,我输入 ctrl+c 尽管给出:

for thread in threads:
    thread.alive = False
    thread.join()
    sys.exit(e)

在代码中,线程继续运行,说线程必须下载,即使在keyinterrupt之后它仍然继续下载。如何优雅地退出代码?

这是完整的代码:

 try:
    threads = []
    while len(list1) != 0:
        while len(threads) != 4:
            time.sleep(1)
            item = list1.pop(0)
            thread = threading.Thread(target=func, args=(item, ))
            threads.append(thread)
            thread.start()
        for thread in threads:
            thread.join()
        for thread in threads:
            if not thread.is_alive():
                # get results from thread
                threads.remove(thread)
        if len(list1) == 0:
            logging.error("Nothing")
            sys.exit(1)
except KeyboardInterrupt as e:
    logging.error("Keyboard Interruption, code exiting!!")
    list1.append(item)
    logging.info(f'{item} Adding back to the list')
    # whenever there is a keyboard interrupt kill all the threads
    for thread in threads:
        thread.alive = False
        thread.join()
        sys.exit(e)
except Exception as e:
    logging.exception(f'Failed to initiate the threads : {e}')
    sys.exit(1)

【问题讨论】:

    标签: python python-3.x multithreading exception keyboardinterrupt


    【解决方案1】:

    除非线程真正关心标志,否则设置thread.alive = False 不会做任何事情。如果你想优雅地终止,你需要修改你的目标func,定期检查alive的值,如果是False就停止运行。

    或者,如果您不关心正常关闭并且只希望所有线程在主线程退出时退出,您可以在创建它们时将daemon=True 添加到 Thread 构造函数中。

    【讨论】:

    • 是的,我正在寻找优雅的东西,守护进程可以或可能会突然破坏我的数据。但是我也在权衡这个
    • @DarcyM 为您的目标 func 发布代码——它需要检查 alive 的值并在它变为 false 时进行清理。
    【解决方案2】:

    我认为你需要找到一种方法来杀死一个线程。这通常是不可取的,尤其是当线程正在读取/写入文件时,或者当线程正在处理其他线程时。我建议阅读this post 了解更多详情。

    您可以创建自定义线程包装器来安全地处理停止线程,或者如果您使用multiprocessing 库,您可以调用process.terminate()

    【讨论】:

    • 我无法打开您在上面提供的链接
    • 这很奇怪,它不再起作用了。我会尝试修复它。
    • @DarcyM 问题已修复。
    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 2015-05-29
    • 2021-11-25
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2017-12-29
    相关资源
    最近更新 更多