Re: Is this "thread-safe" in GTK+....



Chris Seberino <seberino spawar navy mil> writes:

> I want to use pthreads to have a thread that just generates
> numbers used by GTK+ in another thread for drawing.
> (pixmap plot of the numbers)
> 
> I believe variables are global with pthreads but
> are there any gotchas to this? Do I need to
> use semaphores? (I must find out what they are first!) :(

There are lots of gotchas with threads. One way to do what you want
without using threads is like this:

typedef struct MyComputation MyComputation;
struct MyComputation {
    
        /* put all your computation's state here */;

        gboolean cancelled_by_user;    
}

gboolean
run_my_computation (gpointer data)
{
        MyComputation *my_computation = data;

        <do one step of your computation> /* don't run for more than
                                             about 10-20 ms if you can
                                             avoid it 
                                           */

        <do your drawing here, or possibly 
         add another idle handler to do it>;

        if (computation is finished || my_computation->cancelled_by_user)
        {
                g_free (my_computation);
                return FALSE;  /* don't call me again */
        }
        else
        {
                return TRUE;   /* please call me again */
        }
}

and then later do

        my_computation = g_new (MyComputation, 1);
        my_computation->cancelled_by_user = FALSE;
        my_computation->... = ...;
        g_idle_add (run_my_computation, my_computation);

This will make sure your application is responsive and in addition
provide these benefits:

        - the user can stop the computation. In the callback for the
          click on "cancel", just do 

                my_computation->cancelled_by_user = TRUE;

        - you can easily have a progress/activity bar

        - you don't have to mess with threads and locking.


If you must use threads for some reason, then you will generally want
to avoid calling gdk and gtk functions from the thread. Instead use
the same trick and 

        g_idle_add (function_that_does_what_do_need_to_do, ...); 

The function_that_does_what_you_need_to_do() can safely call any gtk
and gdk functions it wants to.

Søren



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