D2 weak references

Fawzi Mohamed fmohamed at mac.com
Mon Apr 20 14:10:44 PDT 2009


On 2009-04-20 22:19:42 +0200, Jason House <jason.james.house at gmail.com> said:

> Sean Kelly Wrote:
> 
>> == Quote from Jason House (jason.james.house at gmail.com)'s article
>>> Jason House Wrote:
>>>> 
>>>> 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?
>>> Here's the implementation I'm currently thinking of:
>>> weak ref construction:
>>> Copy pointer into struct without casting
>>> Call rt_attach_dispose_event
>>> weak ref dereference:
>>> copy value into temp var
>>> ** query gc to see if garbage **
>>> If not garbage, Recopy value and return
>>> If garbage set value = null
>>> dispose of weakly referenced obj:
>>> set value = null
>>> The emphasized line is impossible according to the publicized gc 
>>> interface. Given the delayed
>> finalization, I don't see any way around it.
>> 
>> You're guaranteed that the GC will notify you when it finalizes
>> the referenced object, so you shouldn't have to query the GC
>> at all.  Just copy the reference into a GC-scannable location
>> and then if you haven't been notified by the GC that the object
>> was finalized the reference is good.
> 
> Maybe I misunderstood, but I interpreted earlier discussion in this 
> thread to mean the gc did the following steps:
> 1. Pause all threads
> 2. Scan objects to clear marks
> 3. Scan objects to add marks
> 4. Resume all threads
> 5. Scan objects, if no mark then...
>     5a. Call object finalizer
>     5b. Free memory for later use
> 
> Assuming that is correct, any deref of a weak reference is unsafe 
> between steps 4 and 5a. Even though the object may be valid in that 
> window, there's no guarantee that the reference won't be used after 
> step 5b... This would lead to random behavior and seg faults. No 
> self-respecting weak reference library should allow that to happen.
> 
> I hope I got something wrong and weak refs are easier to implement than 
> I'm currently thinking.

I was thinking to add weak refs to tango core, and I also saw this race 
condition.
The only clean way to fix it is to notify while threads are stopped, 
all the rest is really a cludge.

Fawzi




More information about the Digitalmars-d mailing list