Sharing Ref Counted Containers

dsimcha dsimcha at yahoo.com
Wed Aug 4 19:30:39 PDT 2010


== Quote from Jonathan M Davis (jmdavisprog at gmail.com)'s article
> On Wednesday 04 August 2010 18:20:36 Andrei Alexandrescu wrote:
> > On 08/04/2010 08:02 PM, dsimcha wrote:
> > > I noticed that std.container.Array uses completely unsynchronized
> > > reference counting.  Does that mean that it's basically impossible to
> > > share it across threads without introducing race conditions into the
> > > reference counting code, even if you synchronize on other updates?
> > >
> > > Are there any plans to make Array and future ref counted containers
> > > shareable?
> > >
> > >   If not (I'm not saying that making them shareable is necessarily worth
> > >
> > > doing), I think there should be a large warning against casting these to
> > > shared.  Usually, when you cast a data structure to shared, you can write
> > > working code as long as you properly synchronize all updates to the data
> > > structure.  However, because updates to the ref count field are happening
> > > under the hood in an invisible fashion, no matter how properly
> > > synchronized updates to the contents of the ref-counted container are,
> > > you basically can't properly synchronize updates to the ref count field.
> >
> > There are no plans to make Array a shared type. A shared container would
> > have a very different interface to begin with. Sharing Array objects is
> > not recommended.
> >
> > Andrei
> I would have thought that sharing pretty much _any_ type more complex than a
> primitive type without it being synchronized would be a bad idea. And since the
> standard containers obviously aren't going to be synchronized, I would expect
> you to have to wrap them in a class or struct which is synchronized.
> - Jonathan M Davis

But the point I was trying to make is that it's basically **impossible** to safely
share ref counted containers (except maybe if they're completely encapsulated in a
class, **not a struct**,  wrapper).  No matter how careful you are to synchronize
all access, if you pass them around the ref count field will be updated without
synchronization.  This is not an unreasonable limitation.  The purpose of my
original post was just to clarify it and suggest that, if it's going to stay that
way, there should be a very strong, explicit warning in the documentation.


More information about the Digitalmars-d mailing list