On 31.01.2013 23:37, Steven Schveighoffer wrote:
On Thu, 31 Jan 2013 17:31:38 -0500, Rainer Schuetze <[email protected]>
wrote:
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.
Right, but isn't that an issue with having ANY shared variable that
isn't protected by a lock?
True, as soon as you start mutating the variable. In case of simple
reference/pointer without reference count, the change is atomic though
(depending on the CPU or the implementation of "shared") and the reader
thread just gets the old or the new pointer, but never an invalid pointer.
My main point actually was that a lot of people seem to think that
reference counting with atomic incrementing/decrementing the counter
(like it is used in COM) is thread safe in general. I think they are wrong.
I was thinking you had passed the pointer in via a message or something.
I agree, message passing should not have this issue. It needs that
single reference being accessed from different threads.