On 10/13/13 11:19, deadalnix wrote: > On Sunday, 13 October 2013 at 07:03:39 UTC, Rainer Schuetze wrote: >> How do you increment the counter without reading its address? >> > > I assumed that the reference count was in a struct with the data, and > refcounted point to it. > > In this case, if you remove the pointer via a sequencially consistent write > (while keeping a local copy internally) and THEN decrement the counter, the > other thread will access another object (or skip on a null check). Granted > the read is sequencially consistent.
No, if you have two (or more) threads concurrently accessing the object, it is possible that one threads reads the pointer, then sleeps before incrementing the count. Then another thread comes and /destroys/ the object, the memory is reused for something else, or even unmapped. Then the first thread wakes up and incs the counter, which is no longer there, causing a crash or data corruption. But this is only a problem for shared objects, which are accessed without any locking -- it's not a common case at all, and can be dealt with by simply taking a lock *before* reading the reference. (there are many much more complex solutions such as CAS2 or RCU based ones). artur