Re: Is GIOChannel thread-safe?



On Fri, 2003-02-21 at 18:09, rsteinke w-link net wrote:
> > From: Jonas Borgstr?m <jonas codefactory se>
> >
> > Hi,
> >
> > I'm having some problems using the glib event loop and iochannels
> > in a multi-threaded application. The documentation states:
> >
> > "To allow multiple independent sets of sources to be handled in
> >  different threads, each source is associated with a GMainContext. 
> >  A GMainContext can only be running in a single thread, but sources can
> >  be added to it and removed from it from other threads."
> >
> > The application segfaults or hangs after running for a while on SMP
> > machines.
> > I've managed to reproduce this on both linux 2.2 (2 cpu:s) and solaris
> > (4 cpu:s)
> >
> > A simple test-case that triggers this issue on SMP machines can be found
> > here. Or is this test-case doing something "illegal"?
> >
> > http://afs.codefactory.se/~jonas/roadrunner/gsource-test.c
> >
> > This test-case segfaults after a few seconds on the solaris box and
> > within
> > a minute on the linux machine. I haven't been able to reproduce this on
> > single cpu machines.
> >
> > I'm not sure what causes this, but it looks like it can have something
> > to do with that g_io_channel_ref/unref aren't thread-safe.
> >
> > http://afs.codefactory.se/~jonas/roadrunner/giochannel.c-workaround.diff
> >
> > This patch adds a static mutex around the ref and unref functions and
> > that seems to fix this issue, but it is probably not the correct/best 
> > solution.
> >
> > So, what do you think, is this a bug or is gsource-test.c doing
> > something
> > "illegal"?
> >
> > (I'm using glib-2.2.1)
> 
> I believe the canonical answer for this is that most Glib structures
> don't do their own locking, so if you access them in multiple threads
> you need to add your own mutex. Calling ref/unref functions is certainly
> accessing the structures.

Yes, but if you look at the test-case you'll see that
the "g_io_add_watch" and "g_source_remove" calls are protected by a
mutex and "g_iochannel_ref/unref" is called from within glib.

I know that adding locking into g_iochannel_ref/unref probably isn't
the correct solution. I only added that to somehow isolate the cause and
to make it easier to find a "real" solution.

So if GMainLoop (adding/removing sources) is thread safe but GIOChannel
isn't. Then multi-threaded applications have to implement a
g_io_add_watch work-alike (but with locking). correct?

/ Jonas
-- 
Jonas Borgström                  jonas codefactory se
CodeFactory AB                   http://www.codefactory.se/
Office: +46 (0)90 71 86 14





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