3

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()
Vor
  • 33,215
  • 43
  • 135
  • 193
  • There's no such thing as "stop a thread". Create a loop condition that you can set from outside when you receive the `KeyboardInterrupt`. Or create an infinite loop in the main thread to keep the program alive while the other threads are deamon – JBernardo Apr 26 '13 at 14:10
  • maybe someone will need, my answer is in https://stackoverflow.com/questions/73301237/how-to-force-a-thread-to-join-stop-in-python/76544682#76544682 – lam vu Nguyen Jun 24 '23 at 05:28

1 Answers1

6

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.

bereal
  • 32,519
  • 6
  • 58
  • 104
  • 1
    >> Just curious: Should one use a small timeout `0.01` or a comparatively bigger one like `1`. – pradyunsg Apr 26 '13 at 14:18
  • @Schoolboy depends, but in this case the main thread does nothing useful, and `1` would awake it less often and thus would not waste the CPU time just for waiting. – bereal Apr 26 '13 at 14:25