On 31.01.2013 22:37, Steven Schveighoffer wrote:
On Thu, 31 Jan 2013 15:55:11 -0500, Rainer Schuetze <[email protected]>
wrote:
- how do you do reference counting when accessing shared containers in
multiple threads? Consider clearing the last reference to a shared
reference counted object while another thread reads this reference.
With usual atomic operations on the reference count only:
1. the reading thread reads the payload pointer
2. the writing thread reads the payload pointer, decrements the
reference count and frees the array
3. the reading thread increments the reference count, but accesses
the deallocated array.
I would be concerned if a thread can get ahold of a reference counted
pointer without having the counter incremented already on its behalf.
You have to read the pointer to increment the counter to get hold of
the reference.
Right, but where do you get the original pointer from? Wouldn't that
reference have incremented the count?
Any reference that is accessible from multiple threads, e.g. a global
shared variable.
shared(Container) allObjects;
Without any thread having a reference to it, the payload's reference
count is 1. The reading thread above increments the counter when making
a local copy, but the writing thread decrements the counter when
assigning Container.init. If both run concurrently, with the sequence 1
to 3 above, trouble is inevitable.