Ctrl-C即KeyboardInterrupt杀死Python中的线程 [英] Ctrl-C i.e. KeyboardInterrupt to kill threads in Python

查看:383
本文介绍了Ctrl-C即KeyboardInterrupt杀死Python中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读到KeyboardInterrupt异常仅在Python的主线程中引发.我还阅读到子线程执行时主线程被阻塞.因此,这是否意味着 CTRL + C 永远无法到达子线程.我尝试了以下代码:

I read somewhere that KeyboardInterrupt exception is only raised in the main thread in Python. I also read that the main thread is blocked while the child thread executes. So, does this mean that CTRL+C can never reach to the child thread. I tried the following code:

def main():
    try:
        thread = threading.Thread(target=f)
        thread.start()  # thread is totally blocking (e.g., while True)
        thread.join()
    except KeyboardInterrupt:
        print "Ctrl+C pressed..."
        sys.exit(1)

def f():
    while True:
        pass  # do the actual work

在这种情况下, CTRL + C 对执行没有影响.就像它无法收听信号一样.我会以错误的方式理解吗?还有其他方法可以使用 CTRL + C 杀死线程吗?

In this case there is no effect of CTRL+C on the execution. It is like it is not able to listen to the signal. Am I understanding this the wrong way? Is there any other way to kill the thread using CTRL+C?

推荐答案

存在的问题是您正在使用thread1.join(),这将导致您的程序等待该线程完成继续执行.

The problem there is that you are using thread1.join(), which will cause your program to wait until that thread finishes to continue.

主进程始终会捕获信号,因为它是接收信号的主进程,是具有线程的进程.

The signals will always be caught by the main process, because it's the one that receives the signals, it's the process that has threads.

按照您的说明进行操作,基本上是在运行一个没有线程功能的正常"应用程序,因为您启动了1个线程并等待其完成以继续.

Doing it as you show, you are basically running a 'normal' application, without thread features, as you start 1 thread and wait until it finishes to continue.

这篇关于Ctrl-C即KeyboardInterrupt杀死Python中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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