
Emil Wojak wrote:
// pre-thread boost::shared_ptr<const A> ptr(new A);
// reader thread A boost::shared_ptr<const A> p1=ptr; // get the latest value p1->getSomeValue(); p1->getSomeOtherValue(); p1.reset(); // don't need that anymore
// reader thread B boost::shared_ptr<const A> p2=ptr; // get the latest value p2->getSomeValue(); p2->getSomeOtherValue(); p2.reset(); // don't need that anymore
// writer thread ptr.reset(new A); // look Ma! I've brought you something new!
So is the substitution thread-safe? I think it could be, if the steps necessary to do that were taken in the following order: - setting new object's counter to 1 (atomicity irrelevant at this point) - switching internal pointer to point to the new object (atomic) - from now on, reader threads would get the new object - decrementing old object's counter (atomic) - the old object gets released and eventually deleted
No, this is not safe. 1. reader A reads the pointer value 2. writer thread sets new pointer value 3. writer thread deletes old object and count 4. reader A tries to increment the deleted count, bad things happen The proposed additions in http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2007/n2297.html#atomic aim to support this use case, but I haven't implemented them yet.