Re: Thread-safe reference counts.
"David Schwartz" <davids@webmaster.com> wrote in message
news:5b8507d4-e03f-495f-8adc-495bf517bbf5@u10g2000prn.googlegroups.com...
On Apr 1, 9:27 pm, "Chris Thomasson" <cris...@comcast.net> wrote:
Global locking tables can help a decrementing thread atomically release
and
destroy an object when the count has dropped to zero. This is important
because another thread could sneak in and concurrently attempt to
increment
the reference count during this time.
No, another thread can't sneak in and concurrent attempt to increment
the reference count during that time. The decrementing thread is the
only thread that holds a reference to the object, so no other thread
could even find the object. How could it attempt to increment the
reference count to an object it cannot find?
Lets take some standard code into account... How about a PThread
implmentation for a strongly thread-safe counted pointers which can be found
here, it compiles fine:
http://appcore.home.comcast.net/misc/refcount-c.html
(refcount_copy/swap functions; returns non-zero on failure)
These functions are passed pointers to a shared location that in turn
contains a pointer to a refcount object; you can use them like this:
_____________________________________________________________________
extern "C" void userobj_dtor(void*);
class userobj {
friend void userobj_dtor(void*);
refcount m_refs;
int m_state;
public:
userobj(int state, refcount_refs refs = 1)
: m_state(state) {
refcount_create(&m_refs, refs, userobj_dtor, this);
}
};
void userobj_dtor(void* state) {
delete reinterpret_cast<userobj*>(state);
}
static refcount_shared* g_shared = NULL;
struct userobj_thread {
void readers() {
for (;;) {
refcount_local* local;
if (! refcount_copy(&g_shared, &local)) {
userobj* const uobj = (userobj*)refcount_get_state(local);
printf("(%p/%p/%d)-userobj_thread/userobj/userobj::state",
(void*)this, (void*)uobj, uobj->state);
refcount_release(local);
}
}
}
void writers() {
for (int i = 0 ;; ++i) {
userobj* const obj = new userobj(i);
refcount_local* local = &obj->m_refs;
if (! refcount_swap(&g_shared, &local)) {
refcount_release(local);
}
}
}
};
_____________________________________________________________________
Please check out the 'refcount_copy()/swap()' functions. How would implement
those API's differently? The readers are acquiring pointers to objects that
did not previously own a reference to. IMHO, the locking table is a good
synchronization scheme to use in this scenario.
[...]