Python:防止信号传播到子线程 [英] Python: prevent signals to propagate to child threads
问题描述
import threading
import time
def worker(i):
while True:
try:
print i
time.sleep(10)
break
except Exception, msg:
print msg
threads = []
for i in range(10):
t1 = threading.Thread(target=worker, args=(i,))
threads.append(t1)
for t in threads:
t.start()
print "started all threads... waiting to be finished"
for t in threads:
t.join()
如果我在线程运行时按^ C,该线程是否获得SIGINT?
如果是这样,我可以从调用者线程中做什么来阻止它传播SIGINT到正在运行的线程?
if i press ^C while the threads are running, does the thread gets the SIGINT?
if this is true, what can i do from the caller thread to stop it from propagating SIGINT to running threads?
调用方线程中的信号处理程序会阻止它吗?
还是每个线程都需要信号处理程序?
signal handler in caller thread would prevent it?
or do i need signal handler for each thread?
推荐答案
如果我在线程运行时按^ C,该线程是否获得SIGINT?
if i press ^C while the threads are running, does the thread gets the SIGINT?
不.在Python中,只有主线程才能接收SIGINT.
No. In Python, only the main thread receives the SIGINT.
不幸的是,我不知道在python源代码或要链接的文档中有什么好地方,但是您可以通过一个简单的测试就知道这是正确的:
Unfortunately, I don't know of a good place in the python source or docs to link to, but you can see that this is true with a simple test:
import threading
import time
def worker():
while True:
print('Worker working')
time.sleep(0.5)
pass
worker_thread = threading.Thread(target=worker)
worker_thread.start()
while True:
print('Parent parenting')
time.sleep(0.5)
使用^ C发送SIGINT之后,您将看到主线程被杀死(不再有父母育儿"日志),并且子线程继续运行.
After you send SIGINT with ^C, you will see that the main thread is killed (no more 'Parent parenting' logs) and the child thread continues to run.
在您的示例中,子线程退出是因为您break
在10秒后退出了它们的while
循环.
In your example, your child threads exit because you break
out of their while
loops after 10 seconds.
这篇关于Python:防止信号传播到子线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!