this question has answer here:
- is there way kill thread in python? 19 answers
i did little search , found out there no way kill thread in python, how 1 solve problem me ?
i have function sets x true 1 hour , after sets false.
sometimes program finishes less needed hour, thread still running , make garbage in memory.
def enablex(): self.x=true sleep(3600) self.x=false def function1(): self.enablexthread=thread(target=self.enablex) self.enablexthread.start()
any idea ? how can kill enbablexthread when program terminates no matter if thread done or not ?
how can kill enbablexthread when program terminates
if thread not have cleanup do, make daemon thread setting enablexthread.daemon
true
. must done before starting thread:
self.enablexthread = thread(target=self.enablex) self.enablexthread.daemon = true self.enablexthread.start()
otherwise, use exit flag (a global variable threads check see whether should exit) or event
handler.
you might considering using signal this, may simpler threading; can set alarm hour , have handler reset variable. if process ends before alarm goes off, nothing happens. note isn't available on windows.
import signal x = false def handle_alarm(signum, frame): global x x = false signal.signal(signal.sigalrm, handle_alarm) def set_x_true_then_false_later(secs=3600): global x x = true signal.alarm(secs)
Comments
Post a Comment