Is D associative array thread safe, and will it relocate memory when add or delete a value?
Jonathan M Davis
jmdavisProg at gmx.com
Wed Dec 7 01:00:34 PST 2011
On Wednesday, December 07, 2011 09:10:16 Martin Nowak wrote:
> On Wed, 07 Dec 2011 08:59:32 +0100, raojm <raojm at 91ne.com> wrote:
> > Is D associative array thread safe, and will it relocate memory when
> > add or delete a value?
> >
> > Where I can find the implemention.
>
> No it's not, and yes it has to relocate memory.
> It's working as a hashtable not a binary tree, so all
> pointers will be invalidated by adding/removing.
> https://github.com/D-Programming-Language/druntime/blob/master/src/rt/aaA.d
Yeah. AFAIK, it's impossible to have a hash table which doesn't risk
reallocating something when adding a value to it, unless you limit how many
elements it can hold or somesuch, which would make it considerably less
useful. Typically, when a hash table gets full enough, it rehashes itself,
which definitely involves allocating more memory, and possible reallocating a
large portion of what it's already allocated. So, there's no way that an AA
can avoid the risk of reallocating when elements are added to it, pretty much
regardless of its implementation. It's an attribute of the data structure.
But since adding to a hash table obviously isn't going to be atomic, there's
no way that it's going to be thread-safe regardless. It would have to have to
be using a mutex internally or be synchronized, and there's no way that the
built-in AA is going to do that. It would harm efficiency in the general case
for a special case. If you're using a shared AA and want to ensure thread-
safety, you're going to have to use mutexes or synchronized blocks or whatnot
to ensure that only one thread is using it at a time.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list