Johann Gomes
Johann Gomes

Reputation: 4163

Timer objects in Python

i have a question about Timer object in Python: https://docs.python.org/2/library/threading.html#timer-objects

This object is basically a Thread that calls a specific function after an amount of user defined seconds. My question is: after the function call, the Thread object is automatically eliminated of the program, or this object keeps running, consuming memory?

This snippet of code shows what i'm talking about:

from threading import Timer
from random import randint

def call_function(x):
    print "Timer number " + str(x) + " hit call function!"

for x in range(200000):
    #memory used: 700.000 K
    print "Creating timer number: " + str(x)
    Timer(randint(1, 10), call_function, [x]).start()

After 200.000 threads Timer created and being called in a space of 10 seconds (after this call they were supposed to be dead, releasing space, right?), the program end it's execution with 700.000 K of memory consumption, almost 1 GB.

Thanks,

Upvotes: 1

Views: 1511

Answers (1)

ndpu
ndpu

Reputation: 22561

Timer is just a Thread subclass (created by factory function named Timer) with simple run method:

class _Timer(Thread):
    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

thread terminates just after the run() method terminates:

Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception. The is_alive() method tests whether the thread is alive.

timer class object itself should be garbage collected automatically if it will not be used later.

And you cant start 200000 threads, its too much (_Timer object will be created but thread will not start). Check this question: How many threads is too many?

Upvotes: 2

Related Questions