
Talbot, George wrote:
So that seems like a bit of a useless guarantee--basically any structure constructed with shared_ptr can only be read by the same thread that's writing to the structure unless all of the pointer operations are guarded with a mutex or spinlock, right?
Or an rwlock. Correct, the guarantee isn't useful for writing lock-free code.
Ignoring compare-and-swap, have you or anyone else experimented with using a spinlock (as you mentioned previously) to remove the above restriction? What would that do to performance and complexity? Could you use a compare-and-swap type of operation to implement read/write thread safety?
The atomic operations would look like: shared_ptr copy( shared_ptr const & p ) lock spinlock for p shared_ptr r = p; unlock spinlock for p return r void replace( shared_ptr & p, shared_ptr q ) lock spinlock for p p.swap( q ); unlock spinlock for p bool compare_and_swap( shared_ptr & p, shared_ptr const & cmp, shared_ptr xchg ) lock spinlock for p bool r = p == cmp; if( r ) p.swap( xchg ); unlock spinlock for p return r; The critical regions are comfortably short, so using a spinlock seems justified. One problem is that shared_ptr doesn't have space for a spinlock, so we'd need to use a hashed spinlock pool keyed on 'this'. Or it might be possible to reuse the pointer as a spinlock, using something like (void*)-1 as the 'locked' state. I haven't prototyped it, but it seems workable.