简体   繁体   中英

How to stop a thread python

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM