Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - why does time.sleep cause memory leak?

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()
like image 618
tanglong Avatar asked Jan 19 '16 10:01

tanglong


People also ask

What causes memory leaks in Python?

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.

What does Python time sleep do?

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.

How do you fix a memory leak in Python?

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.

Does Python sleep block?

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.


1 Answers

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.

like image 179
CoMartel Avatar answered Oct 13 '22 21:10

CoMartel