What's an easy way to run a function in the thread with the main loop? [GTK 2.x]

GTK+ FAQ
<<< Previous | Development with GTK+: general questions | Next >>>

# What's an easy way to run a function in the thread with the main loop? [GTK 2.x]

Sometimes the simplest way to set up a threaded program is to make all the GTK+ calls in a single thread. In such a program, you should still call g_threads_init(), but don't need to call gdk_threads_init(), gkd_threads_enter(), and gdk_threads_leave().

If you set your program up this way, how then do you get the thread making GTK+ calls and running the main loop to do something in response to another thread?

An easy way to do it is to take advantage of the fact that the GLib main loop functions are all thread safe, and can be called from any thread by adding an idle function with g_idle_add(). The function provided will be called at the next opportunity by the main thread. If you want your function to take priority over event handling and drawing, you can instead use g_idle_add_full() and pass in a priority of G_PRIORITY_HIGH.

<<< Previous | Home | Next >>>
I'm doing some stuff with GTK+ in a separate thread, and properly locking with gdk_threads_enter/gdk_threads_leave() but the display doesn't update properly. [GTK 2.x] | Up | Why does this strange 'x io error' occur when I `fork()` in my GTK+ app? [GTK 2.x]