停止子线程中的主线程 [英] Stop a main thread from child thread

查看:86
本文介绍了停止子线程中的主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python程序,在主要功能中,我正在启动一个连续运行的线程.启动线程后,主函数进入while循环,在此循环中持续接收用户输入.如果子线程中有异常,我也想结束main函数.最好的方法是什么?

I am writing a python program, In main function I am starting a thread which runs continuously. After starting the the thread the main function enters a while loop where it takes user input continuously. If there is a exception in child thread I want to end the main function also. What is the best way to do that?

预先感谢

推荐答案

让线程控制"其父代不是一个好习惯.对于主线程来说,管理/监视/控制它启动的线程更有意义.

Having a thread "controlling" its parent is not a good practice. It makes more sense for the main thread to manage/monitor/control the threads it starts.

所以我的建议是您的主线程启动2个线程:您已经拥有的一个线程,该线程在某个时候完成/引发异常,以及一个读取用户输入.现在,主线程等待( join s)等待前者完成,并在完成后退出.

So my suggestion is that your main thread starts 2 threads: the one you already have, which at some point finishes/raises an exception, and one reading user input. The main thread now waits (joins) for the former to finish, and exits once done.

from threading import Thread
import time

class ThreadA(Thread):
    def run(self):
        print 'T1: sleeping...'
        time.sleep(4)
        print 'T1: raising...'
        raise RuntimeError('bye')

class ThreadB(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
    def run(self):
        while True:
            x = raw_input('T2: enter some input: ')
            print 'GOT:', x

t1 = ThreadA()
t2 = ThreadB()
t1.start()
t2.start()
t1.join()  # wait for t1 to finish/raise
print 'done'

由于ThreadB是守护程序,因此我们不必显式使其停止或加入它.当主线程退出时,它也会退出.

Since ThreadB is daemonic, we don't have to explicitly make it stop, nor to join it. When the main thread exits, it exits as well.

IMO,无需诉诸信号之类的低级内容.该解决方案甚至不需要使用 try-except (尽管您可能决定要在 ThreadA 中使用 try-except 使其退出干净地).

IMO, there's no need to resort to low-level stuff like signals. This solution doesn't even require using try-except (though you may decide you want a try-except in ThreadA, to make it exit cleanly).

这篇关于停止子线程中的主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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