Re: thread safe gtk?



Owen Taylor <otaylor@gtk.org> writes:

> The problem is, gtk_main_iteration() will just block on the select()
> until an event happens, without regard to the desires of the other
> threads. I don't think you can get this sort of thing working
> properly without basically modifying the main loop. (One approach
> which avoids putting threading dependent code into GTK+ is to allow
> the application to supply a replacemnt for select())

Good point.  I wasn't very familiar with what's going on in gtk_main,
but I just had a look, and I agree, we have to have some *minor*
hackery in gdk_event_wait.  Do you think this would be acceptable
upstream?

As a proposal, here's one potential solution (essentially like yours).
First of all, we need to move everything into gdk, so gdk won't depend
on gtk.  We can still have gtk macro wrappers if we like...

Then a minor modification to gdk.c:gdk_event_wait()

  gdk_event_wait() {
    ...
#   ifdef GDK_THREADS_AWARE  
    if(gdk_using_threads) gdk_threads_leave();
#   endif
    nfd = select (max_input+1, &readfds, &writefds, &exceptfds, timerp);
#   ifdef GDK_THREADS_AWARE  
    gdk_threads_enter();
#   endif
    ...
  }

And an equally minor modification to gdk_threads_init():

  void
  gtk_threads_init (void)
  {
    gdk_using_threads = TRUE;
  }

No more pipes, and exactly the behavior we want.  If the user doesn't
call it, there's no penalty.  Even if they do, there's very little.

> I'm not sure how important fairness is here. Hopefully, a meaningful
> threaded application would be doing enough stuff without the
> lock so that things should balance out fairly well. (My test
> program suffers fairly badly from fairness, but it isn't
> representative).

The problem here is that (I think) two threads can dominate the lock.
If they are both trying to get it in tight loops, and there a third
thread that wants it too, the third thread can sit at the back of the
mutex queue for an arbitrarily long time while the LIFO scheduling
just lets the two other threads hand off to each other.  I'm not sure
we'd have this problem, but we should investigate, and if it's a
problem, prevent it, so that someone else doesn't have to figure it
out the hard way.

-- 
Rob Browning <rlb@cs.utexas.edu>
PGP fingerprint = E8 0E 0D 04 F5 21 A0 94  53 2B 97 F5 D6 4E 39 30



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