Threaded gtk+ apps (Was: making buttons disable and enable)



The best two ways I've found to use gtk+ in a multithreaded program are
(1) mutexes and (2) passing workload back to the main thread.  The newsreader
Pan beats these two ideas to death, and may be useful as sample code.

For (1), the lock in question is gdk_threads_enter() and gdk_threads_exit().
See http://cvs.gnome.org/lxr/source/pan/pan/util.c#109 for the source code
for this.

For (2), Pan uses gtk_idle_add to push back work that can wait for a half-second or
so.  The gtk_idle_add() call needs to be inside the gdk_thread lock, as does any
gtk work done in the idle function.  Pan's titlebar and menu refreshing functions at
http://cvs.gnome.org/lxr/source/pan/pan/gui.c#1805 and 
http://cvs.gnome.org/lxr/source/pan/pan/gui.c#1597 show examples of this.

The gtk+ faq discusses writing threaded apps with gtk+ as well.  It states (and I'll
confirm) that you have to have a gdk_thead lock inside nonmain threads and inside
timeout/idle funcs, but not in gtk callbacks.

I'd advise against hacking the gtk loop if you can help it.

cheers,
Charles

PS. isn't KFind a Qt app? :)


> thanx Mihai for ur ideas
>         but i think there has to some other way for accomplishing this job, i.e.
> calling GTK+ function calls from other thread.
>         if what u say is true then how is it possible that in 'kfind' tool the
> 'start search' tool button remains disabled as long as the search is going on and as
> soon as the search stops it resumes.
>         is there any way to hack the 'gtk_main' thread???


>> Gtk+ is _not_ yet thread-safe, AFAIK (and I think it will not be so very
>> soon).  This means that you cannot make Gtk+ function calls from another
>> thread but the main thread.  Some people think this is a limitation, I
>> personally think it's good; it it were thread-safe, it would be much
>> slower, less portable, etc.  However, you can avoid problems by using
>> mutexes to protect Gtk+ calls, or (probably better) -- call Gtk+ from a
>> single thread.  This can be achieved using some sort of communication
>> mechanism between threads, and when another thread needs to call a Gtk+
>> function notify the main thread, which will do the shit..
>>
>> I hope I'm not wrong (I had the same problems too, but I gave up before
>> solving them.. :)




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