Re: using threads with GTK+



Soeren Sandmann wrote:
Paul Pogonyshev <pogonyshev gmx net> writes:
I'm going to use the following threads with GTK+:
  - thread 1 does all GUI job (widgets etc.) and launches more threads
    when needed;
  - threads 2, ... (launched by 1) do some time consuming computations
    and inform thread 1 once they are done so it can present the results
    to user.

The only thing i'm not sure how to implement is how to let thread 1 know
when one of working threads is finished.  Current best way i found while
studying GTK+ and Glib manuals is like this:

Thread 1 uses a new event source in its the main loop which pops events
from a GAsyncQueue.  Once a working thread finishes it jobs, it pushes a
structure onto the queue, calls g_main_context_wakeup() to wake thread 1
up if needed, and terminates.

This does not seem to be very hard to implement, but before starting on
it, i would like to be sure i didn't miss some more simple way of
implementing the schema above.

A possibly simpler scheme is to g_idle_add() a function when a worker
thread is done with its calculations. That will automatically take
care of waking the main loop and do the necessary locking. You can
count of s sequence of g_idle_add()'s to be executeded in order, so
the "GASyncQueue" will be implicit, and you won't need your own custom
GSource.

This would be possible i think, but it works already, so the question is
now theoretical only (for me at least).  But thanks for the suggestion.

Another possibility is to do all your computation in idle functions
that do a little computation (maybe for 10ms), then return TRUE. That
way you'll get more control over what runs when. This makes it easier
to make sure your GUI thraed doesn't get starved (it will never block
for more than 10 ms), and canceling a computation will be easier. On
the other hand, you'll have to do more work yourself, and the
computations can't be distributed on more than one CPU.

Yes, this is a known approach, but is often difficult to implement and
is not very robust.  Besides, the function that does the main job is
completely separated from GUI (this is my understanding of good design)
and therefore doesn't even know about threads, event loops or whatever.

Paul




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