使用键盘中断关闭所有线程 [英] Closing all threads with a keyboard interrupt

查看:74
本文介绍了使用键盘中断关闭所有线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里试图做的是使用键盘中断来退出程序中所有正在进行的线程.这是我的代码的精简版本,其中创建了线程:

What I'm trying to do here is use a keyboard interrupt to exit all ongoing threads in the program. This is a pared down version of my code where the thread is created:

for i in taskDictionary:
    try:
        sleep(60)
        thread = Thread(target = mainModule.executeThread)
        thread.start()
    except KeyboardInterrupt:
        thread.__stop()

程序本身要复杂得多,需要考虑大量影响线程的不同变量,甚至可以选择以顺序模式启动,在顺序模式下,任务没有线程,而是一个一个地启动,因此可能我刚刚想到的这个小变化会带来一些问题. 我这样做的方式产生了50/50的结果.中断将起作用,但线程将永远不会干净退出.有时他们会继续前进,但停止执行将来的线程,有时它们会退出有关中断的大量错误,而另一些时候,中断根本不会执行任何操作.上一次我运行该程序时,该程序停止了将来任何线程的执行,但没有停止当前线程. 是否有任何方法可以退出线程而无需进入线程实际在其中执行的模块?

The program itself is far more complicated, accounting for tons of different variables that affect the threads and even having the option to launch in a sequential mode, where tasks are not threaded, but instead launched one-by-one so there might be some problems with this small variation I just conjured up. I have done this in ways that produced 50/50 results. The interrupts would work but the threads would never cleanly exit. Sometimes they would keep going but halt the execution of future threads, some times they would exit with a massive error regarding the interrupt, other times the interrupts would do nothing at all. Last time I ran this the program stopped any future threads from executing but did not stop the current thread. Is there any way to exit the threads without going into the module the thread is actually executing in?

推荐答案

类似的问题是如何杀死线程?"

A similar question is "How do you kill a thread?"

您可以在线程中创建退出处理程序,该处理程序由线程模块中的锁或事件对象控制.然后,您只需删除锁或向事件对象发出信号.这通知线程它应该停止处理并正常退出.在主程序中发出线程信号后,剩下要做的就是在main中使用thread.join()方法,该方法将等待线程关闭.

You create an exit handler in your thread that is controlled by a lock or event object from the threading module. You then simply remove the lock or signal the event object. This informs the thread it should stop processing and exit gracefully. After signaling the thread in your main program, the only thing left to do is to use the thread.join() method in main which will wait for the thread to shut down.

一个简短的例子:

import threading
import time

def timed_output(name, delay, run_event):
    while run_event.is_set():
        time.sleep(delay)
        print name,": New Message!"


def main():
    run_event = threading.Event()
    run_event.set()
    d1 = 1
    t1 = threading.Thread(target = timed_output, args = ("bob",d1,run_event))

    d2 = 2
    t2 = threading.Thread(target = timed_output, args = ("paul",d2,run_event))

    t1.start()
    time.sleep(.5)
    t2.start()

    try:
        while 1:
            time.sleep(.1)
    except KeyboardInterrupt:
        print "attempting to close threads. Max wait =",max(d1,d2)
        run_event.clear()
        t1.join()
        t2.join()
        print "threads successfully closed"

if __name__ == '__main__':
    main()

如果您真的需要杀死线程的功能,请使用多处理.它允许您将SIGTERM发送到各个进程"(它也与线程模块非常相似).一般来说,线程是针对您的IO绑定,而多处理则是针对您的真正的处理器绑定.

If you REALLY need the functionality of killing a thread, use multiprocessing. It allows you to send SIGTERMs to individual "processes" (it's also very similar to the threading module). Generally speaking, threading is for when you are IO-bound, and multiprocessing is for when you are truly processor-bound.

这篇关于使用键盘中断关闭所有线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆