D2 weak references

Sean Kelly sean at invisibleduck.org
Mon Apr 20 12:57:53 PDT 2009


== Quote from Jason House (jason.james.house at gmail.com)'s article
> Sean Kelly Wrote:
> > Daniel Keep wrote:
> > >
> > > Sean Kelly wrote:
> > >> Jason House wrote:
> > >>> Jason House wrote:
> > >>>
> > >>>> Tango's GC (and therefore
> > >>>> druntime's GC) has an explicit notification mechanism.
> > >>> I guess I shouldn't have assumed that the features of tango became
> > >>> part of druntime.  I don't see any notification mechanism :(
> > >> Same as Tango:
> > >>
> > >> alias void delegate(Object) DEvent;
> > >> extern (C) void rt_attachDisposeEvent(Object h, DEvent e);
> > >> extern (C) void rt_detachDisposeEvent(Object h, DEvent e);
> > >>
> > >> I should probably expose these in core.runtime.
> > >
> > > How are these events dispatched?  I remember a discussion about race
> > > conditions if these events were fired off after all threads had been
> > > resumed; you could have the event zero out the weak ref AFTER something
> > > else had dereferenced it.
> >
> > It's the responsibility of the person making the weak ref to make it
> > thread-safe if that's a design consideration.  If the cleanup is
> > performed before the threads are restarted and the weak ref (or
> > signal/slot mechanism) uses mutexes then a deadlock is possible.  At
> > least this approach provides the option for correct code to actually work.
> >
> > > If that's still a possibility, maybe you could add a case where if the
> > > delegate's funcptr is null, it just assumes the context pointer points
> > > to a void*.sizeof word and zeroes it out.  You could do that without
> > > resuming threads.
> >
> > This is all tied into the finalizer.  To do what you suggest the GC
> > would have to perform two sweeps--one before resuming threads and one after.
> If I understand you correctly, a weak reference library needs to query the GC to see if an object is marked for collection.
How do I do this?

I think the WeakRef just has to either wrap the deref operation in a synchronized
block if it's intended for multithreaded use or perform an atomic read and update
of the reference.  From my understanding, the problem Daniel Keep describes above
is simply an issue of the referenced object vanishing at the same instant someone
tries to access it through the WeakRef.  The same thing could happen if someone
explicitly deletes the object instead of letting the GC clean it up.



More information about the Digitalmars-d mailing list