如何停止线程python [英] How to stop a thread python

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

问题描述

大家好,

我试图在程序停止时停止这个线程(比如当我按下 ctrl+C 时),但没有运气.我试过 put t1.daemon=True 但是当我这样做时,我的程序在我启动后就结束了.请帮我阻止它.

I'm trying to stop this thread when program stops (like when I press ctrl+C) but have no luck. I tried put t1.daemon=True but when I do this, my program ends just after I start it. please help me to stop it.

def run():
    t1 = threading.Thread(target=aStream).start()

if __name__=='__main__':
    run()

推荐答案

一种常见的做你想做的事情的方法,就是加入线程一段时间,就像这样:

One common way of doing what you seem to want, is joining the thread(s) for a while, like this:

def main():
    t = threading.Thread(target=func)
    t.daemon = True
    t.start()
    try:
        while True:
            t.join(1)
    except KeyboardInterrupt:
        print "^C is caught, exiting"

在带有超时的循环中执行此操作很重要(不是永久的 join()),因为信号仅由主线程捕获,因此如果主线程被阻塞,则永远不会结束.

It is important to do this in a loop with timeout (not a permament join()) because signals are caught by the main thread only, so that will never end if the main thread is blocked.

另一种方法是设置一些事件,让非守护线程知道何时完成,这对我来说似乎更令人头疼.

Another way would be to set some event to let the non-daemon threads know when to complete, looks like more of headache to me.

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

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