问题描述
我在某处读到KeyboardInterrupt
异常仅在Python的主线程中引发.我还阅读到子线程执行时主线程被阻塞.因此,这是否意味着 + 永远无法到达子线程.我尝试了以下代码:
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 + 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
在这种情况下, + 对执行没有影响.就像它无法收听信号一样.我会以错误的方式理解吗?还有其他方法可以使用 + 杀死线程吗?
In this case there is no effect of + 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 +?
推荐答案
存在的问题是您正在使用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中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!