Re: g_idle_add and thread safety



On 6/4/07, Gabriele Greco <gabrielegreco tin it> wrote:
The question I have and which I didn't find answers both googling, both
looking at the sources is if g_idle_add can be called without any extra
mutex/lock from another thread.

Yes, this works fine. You do need to init the threads system, but of
course you will have to do that before you can call g_thread_create()
to make your worker.

Ideally my code should be something like:

I think the best way to do this is model-view style.  So your worker
thread does this:

my_thread()
{
  for(;;){
    // worker thread main loop
    Thing *stuff;

    stuff = g_new( Thing, 1 );
    calculate_thing( stuff );
    g_idle_add( handle_stuff, stuff );
  }
}

Then the function handle_stuff will be run by your program's main loop
thread when it's next idle:

gint
handle_stuff( Thing *stuff )
{
  update_model( stuff );
  g_free( stuff );
  return( FALSE );
}

Update_model() uses the calculated data to update the data structures
underlying your program, but does not try to update the display.

Instead it adds another idle handler (cancelling the previous one, if
any) which will update all the screen widgets from the underlying
data.

John



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