Re: Instabilities with multi threaded application



Soeren Sandmann wrote:

Tiago Cogumbreiro <cogumbreiro linus uac pt> writes:
Are g_{idle,timeout}_add add thread safe? Can i call them from another
problems with no problems whatsoever? I'm am routing all my gui related
tasks to these functions and therefore skiping the gdk lock, is this an
acceptable procedure?
Yes, calling g_idle/timeout_add from another thread is perfectly
legal. Those functions will do their own locking, so
gdk_threads_enter/leave() are no not needed. And yes, routing all gui
related tasks though those functions is acceptable and what I'd
usually recommend for using threads with GTK+.
this is not quite correct. g_idle/g_timeout functions are called outside the gdk global lock, and so if you use gtk or gdk in a timeout function, you _must_ enclose such calls in gdk_threads_enter/leave() pairs. now, as above, if only the main thread is touching the GUI, you don't need to worry about it. but if, if you're only making gdk/gtk calls from the main thread or in g_idle/g_timeout callbacks (assuming you have _only one_ main loop in the main thread), then you should be ok.

now, on the contrary, glib itself _is_ thread-safe, so the simple act of calling g_idle_add() or g_timeout_add() in a 2nd thread won't cause problems without locking. it's just if you're doing GUI stuff in more than one thread and in the timeout/idle functions, then you need to do the gdk_threads_* stuff in the idle/timeout function.

to summarise:
* glib itself (e.g., the main loop) is totally thread-safe
* gtk signal callbacks are called inside the gdk lock
* g_idle/g_timeout callbacks are called _outside_ the gdk lock, and so gdk_threads_enter/leave() pairs are required if:
 - you call gdk/gtk functions in the timeout/idle function
 - any other thread but the main thread calls gtk/gtk functions

even if that last condition isn't met, it's probably safer to do it anyway if you're going multithreaded, as you never know what you might change later.

There is no need for gdk_threads_enter/leave() in the callbacks either
since they will be called from the main gtk+ thread. Of course, if the
callbacks are accessing data structures that are modified by other
threads, then locking will be needed,
this _is_ correct, as gtk signals are indeed handled inside the gdk global lock.

   -brian



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