Below Python code generates memory leak.
Challenge: Fix the memory leak with minimal changes to the code as measured by Levenshtein distance to the original code. You may only change the code before
t is initialised. When the
del t line is removed the modified program should print
I'm still alive! every second.
PS: I already know the answer (found it after several hours of debugging). This is not the programming help question! Hopefully this would be interesting to folks.
import threading, time # this class takes callback and calls it every 1 sec class MyTimer: def __init__(self, callback): self.callback = callback self.th = threading.Thread(target=self.run,daemon=True) self.th.start() def run(self): while(True): self.callback() time.sleep(1) class TestMyTimer: def __init__(self): self.timer = MyTimer(self.is_alive) def is_alive(self): print("I'm still alive") # test code for MyTimer t = TestMyTimer() del t # just to be sure to collect all dead objects import gc gc.collect() # if you are still seeing messages then we have memory leak! time.sleep(60)
Here's repl.it to play with this code online.