Re: Thread-safe reference counts.
"Chris Thomasson" <cristom@comcast.net> wrote in message
news:LaadnfT7G6mXgmvanZ2dnUVZ_viunZ2d@comcast.com...
"Jon Harrop" <jon@ffconsultancy.com> wrote in message
news:aKydnRvbbppChmvanZ2dnUVZ8qbinZ2d@plusnet...
Chris Thomasson wrote:
[...]
Reference counting on the other hand, barring cycles,
can destroy that object _immediately_ after the count reaches zero.
The value can be unreachable before the count reaches zero.
WRONG! WRONG! WRONG! WRONG! ROFL!
There are reference(s) to the object which is keeping the count above
zero. Therefore the object __IS__ reachable.
In the example I gave:
{
Bar bar;
f(bar);
// *
g();
}
At * there are zero references to "bar" but its reference count is one.
Your making the mistake of creating Bar on the stack. We are talking about
dynamically created objects:
{
refcount<Bar> this_is_ref_to_bar(new Bar);
f(this_is_ref_to_bar);
g();
}
There is a single live reference to the Bar object, it is indeed
reachable.
[...]
Even a GC would consider an object reachable that has a reference count
equal to 1. If there is a pointer to an object, then its still being used.
When that pointer drops out of scope, or gets set to NULL, then the object
is not able to be reached by anything, and therefore can be reaped.
If you think that you can destroy objects with a reference count of 1, well,
you better be sure that the owner of the reference does not try and use it
during/after you kill the object. Only the programmer can know what the
owner of the reference is going to do. For instance, there is an
optimization that you can do for reference counting algorithms that provide
basic-thread safety:
void refcount_release(refcount* const _this) {
atomicword const refs = ATOMIC_LOADWORD(&_this->refs);
if (refs > 1) {
if (ATOMIC_DEC(&_this->refs) > 0) {
return;
}
}
free(_this);
}
The compiler could possible learn these details from the program as it
compiles it.