Medya Gh Medya Gh - 2 months ago 7
Python Question

killing a thread in python before its done

I did a little search and found out there is no way to kill a thread in python, but how would one solve a problem like me ?

I have a function that sets X to True for one hour and after that it sets it back to False.

sometimes the program finishes less than the needed hour, but the thread is still running and 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 I can kill enbableXThread when the program terminates no matter if the thread is done or not ?

Answer

how I can kill enbableXThread when the program terminates

If the thread does not have any cleanup to do, make it a daemon thread by setting enableXThread.daemon to True. This must be done before starting the thread:

self.enableXThread = Thread(target=self.enableX) 
self.enableXThread.daemon = True
self.enableXThread.start()

Otherwise, use an exit flag (a global variable that the threads check to see whether they should exit) or an Event handler.

You might also considering using a signal for this, as this may be simpler than threading; you can simply set an alarm for an hour and have the handler reset the variable. If your process ends before the alarm goes off, nothing happens. Note that this 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