Package: glib

Function g-main-depth

Lambda List

g-main-depth ()

Return Value

An integer with the main loop recursion level in the current thread.

Details

Returns the depth of the stack of calls to the g-main-context-dispatch function on any context in the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback from the g-main-context-iteration function, or the g-main-loop-run function, etc., it returns 1. When called from within a callback to a recursive call to the g-main-context-iteration function, it returns 2. And so forth.

There is a temptation to use the g-main-depth function to solve problems with reentrancy. For instance, while waiting for data to be received from the network in response to a menu item, the menu item might be selected again. It might seem that one could make the callback of the menu item return immediately and do nothing if the g-main-depth function returns a value greater than 1. However, this should be avoided since the user then sees selecting the menu item do nothing. Furthermore, you will find yourself adding these checks all over your code, since there are doubtless many things that the user could do. Instead, you can use the following techniques:
  • Use the gtk-widget-sensitive function or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.
  • Avoid main loop recursion in situations where you cannot handle arbitrary callbacks. Instead, structure your code so that you simply return to the main loop and then get called again when there is more work to do.
 

See also

2021-12-10