Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 818
Vor Avatar asked Feb 15 '26 19:02

Vor


1 Answers

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.

like image 105
bereal Avatar answered Feb 18 '26 08:02

bereal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!