Re: Recalculation of timeouts with g_timeout_add




Mitko Haralanov a écrit :
On Fri, 16 May 2008 09:54:22 +0200
G Hasse <gorhas raditex se> wrote:

Let your callback return FALSE and reregister before the return

Hi, I thought of that but I was sure that there is a better way to do
this without playing games with unregistering and re-registering the
timeout.

I am not sure why the GTK devs decided that re-calculating the timeout
based on the time right after the timeout thread is started is the
right thing to do but it seems very wrong to me.

I think this is really the best solution. And by the way, this timeout comportment (counting elapsed time since last time the callback was called) is the right thing to do, as it's the most common case. Just because your current problem has different needs doesn't mean it was the wrong choice. How could you trigger an event, say, 10 times per second otherwise (for an animation for example) ?

What if the timeout function takes longer then the timeout itself? You
end up with multiple threads running the timeout function at the same
time.

As already specified, there's only the main thread. GTK doesn't create other threads alone.

Oh, and you should use g_timeout_add_seconds for timeouts > 1s.

For your example, just set the timeout at the end of the callback, and return always FALSE. To set it the first time, just call the callback alone. That way the callback is called 20 seconds after the last callback call ended (I didn't tested the code, but it should work).

#include <gtk/gtk.h>
#include <glib.h>
#include <time.h>
#include <stdio.h>

gboolean callback (gpointer data) {
     int timeout = GPOINTER_TO_INT (data);
     printf ("callback called at: %lu\n", time (NULL));
     sleep (timeout);
     printf ("callback returns at: %lu\n", time (NULL));
     g_timeout_add_seconds (20, callback, GINT_TO_POINTER (timeout));
     return FALSE;
}

int main (int argc, char **argv) {
     int timeout = 10;
     gtk_init (&argc, &argv);
     callback (GINT_TO_POINTER (timeout);
     gtk_main ();
}



Also, you should give a look to GTimer, with is nice to use when you want to measure timings.


Cheers,

Luis



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]