Re: Threading issues



Chris Seaton wrote:
I'm using threads with GTK+ for the first time and having trouble. The
only time I start a new thread is for the (noticeably slow) file save
and open routines.

When the user selects File -> Save the event handler disables the main
window and starts a new thread. The entry point of that thread saves the
file and then enables the main window again.

Frankly speaking, I don't understand why you need another thread if the
window is disabled anyway?  Or do you have another windows which are
accessible at this time?

The save routine (running in the new thread) shows dialog boxes, both
modal and modaless, but both transient on the main window. Is this
simply not allowed?

You probably miss calls to gdk_threads_enter() and gdk_threads_leave().

But I'd like to advertise the multithreading model I use myself ;)

In my application only one thread ever calls GDK/GTK+ functions.  All
other threads are simply not allowed to touch GUI.  When some 
time-consuming job has to be performed the main (GUI) thread launches
a working thread for the job and keeps working with GUI.  When a working
thread finishes, it pushes a structure with two fields (callback and
data) onto an asyncronous queue (implemented in Glib).  The main thread
pops the structure and executes callback in its own context, so that
results of the long working process can be used by GUI.

This model is very simple and error-resistant, because the only
synchronization point is in the asynchronous queue.  Working threads
can even force some GUI operations in the middle of process by pushing
data on the queue.

With this model you can do at least two nice tricks without any
synchronization at all: progress displaying and cancellation support.

For progress displaying, GUI threads updates some widget from time to
time (say, on a timeout) based on some variable, e.g. `progress'.  It
only reads the variable, but never writes it.  A working thread in
turn writes `progress' variable.  Since there is only one writer and
the variable is written in one operation (it should be `int' or other
simple type), no synchronization is needed.  As an advantage, you may
not care about how often you update your progress state, because you
don't lose performance on synchronization or GUI operations.  10000
writes of an `int' per second is not the same as 10000 of widget updates
per second.

Cancellation support is done in the same way except that now GUI thread
is the writer and working thread is the reader which checks state of a
variable.

Hope this helps.

Paul



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