Re: timers



On Sun, Dec 11, 2005 at 07:53:22PM -0500, Travis Miller wrote:
> I have another GLib question.  Currently I am writing some code that
> needs to perform some calculations every second.  SO I want the function
> called every second.  So rather than using setitimer to create a SIGALRM
> event that registering a function with sigaction() would catch, I
> thought I could use the g_timeout_add() function in GLib.  However I
> found after playing with it that if I set it to 1 second then after 1
> second it calls the function.  At the end of the function (if I return
> TRUE from the function) it then sets up to call the function again in
> second.  So for a function that takes say 100 - 200 milliseconds to
> complete, I find that I get the behavior that my function is not called
> every second but more like every 1.1 - 1.2 seconds.  I undertsnad that
> gtk_timeout_add() is deprecated so is there another option (or should I
> just use the standard setitimer() function)?

is g_timeout_add() deprecated?  I don't see anything about that in my
documentation.

I've used both POSIX signals and the g_timeout stuff to run "timers".
Regular POSIX signals are nice because they're more truly asynchronous.
They're bad because you can't manipulate any gtk widgets (the gtk state)
from a POSIX signal callback, because you're likely to receive the
interrupt during a non-thread-safe section.  This is the reason I stick
with the g_timeout stuff.

I think the best way to deal with your issue is to NOT use the automatic
restart feature you're using (return TRUE from the callback).  Instead,
look to see how much time has passed since the last time the callback
ran and use gtk_timeout_add() with an adjusted timeout value.

keep in mind that there is no guarantee that that the timer will fire
"on time".  it will fire as soon as possible, and only during main loop.
So, if one of your functions takes several seconds to complete a task
and doesn't allow gtk events to be processed, your g_timeout callback
will not be called for those several seconds.  I think this is similar
to how POSIX signals work, but they're a little more reliable. :)

- Ben




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