Re: Weak references for GObject



Dan Bornstein <danfuzz milk com> writes:

> Okay, one question before I close. Back to this:
> 
> > object = g_weak_ref_deref (blah->weak);
> > [ do something with object ]
> > g_object_unref (object);
> 
> If this isn't what's currently done, how do you guarantee that a
> weakly-pointed object doesn't get freed out from under you in the middle of
> an operation? Given multiple threads, it's easy to imagine dangerous
> scenarios, but even in the single-threaded case, isn't there the danger of
> an inner call freeing a weakly-pointed object unbeknownst to the caller? Do
> you have to write code like this?:
> 
>     if (weak != null) {
>         ... stuff that isn't function calls ...
>         some_call_that_can_affect_weak();
>         if (weak != null) {
>             ... etc ...
>         }
>     }

The core GTK+ code is usually very careful to do:

  obj = get_some_object ();

  g_object_ref (obj);

  do_something_that_might_call_user_code ();
  do_something_else (obj);

  g_object_unref (obj);

Most users who write GTK+ code aren't nearly as careful, but then
again, the potential weird reentrancy cases usually are pretty limited
in a normal app.

It used to be pretty easy to kill GTK+ by doing the wrong things at
the wrong time, but we've worked hard on bullet-proofing it and gotten
pretty good at writing the code right the first time . I won't claim
that it isn't possible to make GTK+ screw in this way any more, but
you have to be trying fairly hard. (Most of the thanks here go to Tim
"reentrancy" Janik.)

GTK+ is certainly a level of complexity where having real GC would
greatly simplify things and probably provide significant performance
benefits. (We spend a lot of time ref'ing and unref'ing objects and
keeping track of when we need to do so.) However, the need integrate
with other systems has kept us away from that road.

Regards,
                                        Owen
  
  





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