JustClaire
JustClaire

Reputation: 480

Is there a way to have precise timed events in GTK/GLib?

I want to have a function that would run every N milliseconds and i want it to run precisely (relatively, i dont need atomic clock precision). From what i can see, GLib manual says that g_timeout_add() does not guarantee precision and can be delayed due to other events.

Is there any other way to have precise time events with GTK/GLib? I would rather not use platform specific code, as i want my program to work on both Windows and Linux with as few platform related code changes as possible.

Upvotes: 1

Views: 813

Answers (2)

Kevin Boone
Kevin Boone

Reputation: 4307

How precise is "not atomic clock"? In the end, timing precision is going to be limited by factors like the platform's context-switching behaviour. Unless you're using customer kernels or specialist hardware, there might not be much you can do about that.

g_timeout_add() is doubly problematic, because it's operation is tangled up with the GTK event handling mechanism, which was never designed for precision.

In the end, your best bets might be either

  1. Use a conventional, signal-based timer (e.g., from setitimer), or
  2. Spawn a new thread and just usleep() a fixed time between actions.

Both these approaches are problematic in GTK, because it's hard to update the user interface from outside the GTK main context thread. Some fairly complicated locking and inter-thread communication is usually required.

If practicable -- and I have no idea whether it would be -- I would suggest delegating the timing part to some separate process, and have the GTK application interact with it using, e.g., sockets.

Upvotes: 2

nemequ
nemequ

Reputation: 17482

Without more detail g_usleep would probably be your best bet, but keep in mind that it blocks the current thread so if you want other tasks to proceed in parallel you'll need to spawn a new thread to run it in.

Upvotes: 2

Related Questions