Search code examples
pythonmemory-managementglib

GLib timeout memory management


I have a GLib.timeout_add_seconds() timer where I occasionally update the timeout interval, like this:

self.timer_id = GLib.timeout_add_seconds(interval, self.on_timeout, user_data)
...
def on_timeout(self, user_data):
    ...
    if change_timeout_interval:
        self.timer_id = GLib.timeout_add_seconds(new_interval, self.on_timeout, user_data)
        return False
    ...

So the ID for the new timer gets stored in the same self.timer_id variable and the old timer is removed (?) when I return false from the callback. I am worried about memory management, as discussed here, especially because I am passing my user_data variable to the callback function. I only use GLib.source_remove() to remove the "final" timer ID, not all the previous ones that were replaced as shown above inside the callback function. Is this bad? If so, how could I avoid this?


Solution

  • Looks fine to me. At the point you overwrite self.timer_id with the new timer ID, the old one is guaranteed to be eventually removed (and not dispatched again) by returning False.

    Are you seeing any symptoms of problems, such as timers being dispatched multiple times, or leaks being shown by valgrind --tool=memcheck?

    One small note: you can use return GLib.SOURCE_REMOVE rather than return False to make the code a little clearer. They’re equivalent. The converse is return GLib.SOURCE_CONTINUE rather than return True.