Re: Fun with multithreaded gnome application



On 12 Oct, Adam Cherrett wrote:
I've just started on my first GTK+/gnome application, and am very pleased
with the ease with which I'm making progress. However, I've just come up
against an interesting problem.

Because the application involves lengthy computations, it is essential
that I multithread it. 

You could also do fork(2), with a subsequent exec(2). The two programs can
then exchange data with text-based messages via pipes. The advantage of
this approach is that you can test the second application (that performs
the actual calculations) separately, on the command line. It's more work
initially, but it might pay off when debugging time comes, because you can
easily dump the strings that are interchanged between the programs to the
console, to see what's happening.

I've discovered that making any gtk calls from
anything other than the main thread (which is the one running gtk_main())
is doomed to failure. However, I want progress information to be
displayed for one of my computation threads.

Have you tried putting your gtk+ calls in the second thread between
gdk_threads_enter() and gdk_threads_leave() calls? That should work.

Alternatively, you could do your calculations in a callback which regularly
lets gtk+ process events:

while (calc_running) {
        /* do a little piece of the calculation here */
        while (gtk_events_pending())
                gtk_main_ieration();
}

This has some drawbacks though. The time spent in the calculations depends
on the processor speed. Something that feels right on a fast machine might
make the GUI terribly unresponsive on an older machine. Also it mingles
your calculation code with the gtk+ code which you might want to keep
separate because of portibility (or other) reasons.

On the plus side, this code is single threaded, so it's easier to debug.

Secondly, how do I arrange for the gtk main loop to watch the pipe and
run a callback function whenever something arrives?

Use gtk_input_add() or g_io_add_watch().

-- 
Roland Smith                        "When life hands you a lemon,
r s m i t h @ x s 4 a l l . n l      make lemonade."
http://www.xs4all.nl/~rsmith/





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