When I ran the code below, the memory was increasing. However if I deleted time.sleep(3)
, it was 0.1
in top
and never increased.
It seems process
not be terminated correctly, but why?
Code(Python 2.7.11
):
import time
import multiprocessing
def process():
#: FIXME
time.sleep(3)
return
def main():
pool = multiprocessing.Pool(processes=10)
while 1:
pool.apply_async(process)
pool.close()
pool.join()
if __name__ == '__main__':
main()
One of the leading causes of memory leaks across programming languages is the presence of unreferenced objects in the memory. Unreferenced objects are allocated in the memory but the reference to these objects has been deleted in the course of the control flow.
Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds. Notice that python time sleep function actually stops the execution of current thread only, not the whole program.
The use of debugging method to solve memory leaks You'll have to debug memory usage in Python using the garbage collector inbuilt module. That will provide you a list of objects known by the garbage collectors. Debugging allows you to see where much of the Python storage memory is being applied.
The reason you'd want to use wait() here is because wait() is non-blocking, whereas time.sleep() is blocking. What this means is that when you use time.sleep() , you'll block the main thread from continuing to run while it waits for the sleep() call to end.
As far as I know, I think that as you spawn new processes in the same Pool, the garbage collection is never done, so you don't release memory from old processes, even if you are done using them. One fix would be to enforce the garbage collection in your while loop:
import time
import multiprocessing
import gc
def process():
time.sleep(3)
return
def main():
pool = multiprocessing.Pool(processes=10)
while 1:
pool.apply_async(process)
gc.collect()
pool.close()
pool.join()
if __name__ == '__main__':
main()
This fixed the memory leaks for me, as you force the garbage collection before launching another set of processes. I hope someone could explain in a more detailed way the reason behing this memory leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With