How to stop a thread python

元气小坏坏 提交于 2021-01-27 15:13:49

问题


Ho everybody,

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()

回答1:


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"

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.



来源:https://stackoverflow.com/questions/16238396/how-to-stop-a-thread-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!