Reputation: 35149
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()
Upvotes: 3
Views: 1421
Reputation: 34290
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.
Upvotes: 6