Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr and weak_ptr concurrency
From: John Dlugosz (JDlugosz_at_[hidden])
Date: 2009-09-04 15:36:53


> can you point to anything that the boost shared_ptr does that is unsafe
> in the one-writer-multiple-reader case?

Just looking at the header, I see two direct members, px and pn.
So straight assignment isn't going to copy the struct in one atomic operation.

Looking at operator=, I see two separate assignments. First the assignment to the contained pointer takes place. Now, a reader on another thread will see the object to have the wrong shared_count structure. Then, the assigning thread continues, taking its time to crank through the shared_count assignment which changes two reference counts (lengthy pipeline stalls for atomic operations, CPU stays busy for a while) before finally writing the new pn value.

It could be made safe by implementing it like this:

      make a temp shared_ptr object, initialized from the RHS.
      issue a double-wide atomic swap instruction, swapping the LHS for the temp.
      let the temp destruct.

That's machine architecture specific, and compiler specific on how to make it emit the correct swap instruction. The x86 and x64 have an atomic exchange that's twice the size of a normal pointer, so it will swap two pointers in one struct. That's what it's there for -- implementing things like this.

You could easily change the function in shared_ptr.hpp if you wanted it to work that way.

--John

TradeStation Group, Inc. is a publicly-traded holding company (NASDAQ GS: TRAD) of three operating subsidiaries, TradeStation Securities, Inc. (Member NYSE, FINRA, SIPC and NFA), TradeStation Technologies, Inc., a trading software and subscription company, and TradeStation Europe Limited, a United Kingdom, FSA-authorized introducing brokerage firm. None of these companies provides trading or investment advice, recommendations or endorsements of any kind. The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon, this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from any computer.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net