My question is about g_timeout_add_full()
. Here is a small piece of code that I don't understand how it works.
...
g_timeout_add_full(priority1, zero_delay, callback1, ...);
g_timeout_add_full(priority2, zero_delay, callback2, ...);
// priority1 < priority2
...
Will the first callback always be executed before the second? If yes, than how does Glib handle priorities? What will happen if a callback with higher priority is added much later then a lesser priority callback?
Will the first callback always be executed before the second?
In this exact situation, yes.
If yes, than how does glib handle priorities?
Each event source is assigned a priority. The default priority,
G_PRIORITY_DEFAULT
, is 0. Values less than 0 denote higher priorities. Values greater than 0 denote lower priorities. Events from high priority sources are always processed before events from lower priority sources.
What this means is that for each iteration of the GMainContext
, the set of sources ready to be dispatched is queried. From that set, the ones with the equal-highest priority are dispatched, and then that iteration of the GMainContext
ends.
On the next iteration, the process is repeated. The next-highest priority sources are dispatched, unless some higher priority ones have become ready to be dispatched again in the meantime.
In the specific case of timeout sources, timeouts with zero delay are ready to be dispatched in the new main context iteration. Other timeouts (with non-zero delay) will become ready to dispatch when their timeout expires.
I’ve submitted a merge request to expand the GLib documentation slightly around this.
What will happen if callback with higher priority will be added much later then less priority callback?
That depends on when the sources become ready to dispatch, which depends on what type of source they are. If they are timeouts, it depends on their timeout interval.
As above, assuming both sources are ready to dispatch, the higher priority one will be dispatched first.