Memory Allocation and Locking

dsimcha dsimcha at yahoo.com
Fri Aug 22 13:14:29 PDT 2008


But D's malloc appears to require locking even when memory is available, just to
allocate it.  Heck, it even synchronizes to check the capacity of an allocated
block, which (I'm guessing) means every ~= requires a synch if the code is
multithreaded, even if no realloc ends up being necessary.  I base this on reading
the GC implementation.  I assume that allocating via builtin arrays is basically a
thin layer on top of D's malloc.  Here's the Phobos implementation.  For those who
haven't looked at this, the function thread_needLock just returns true if more
than 1 thread is currently running.  Haven't looked at Tango b/c, unfortunately,
it's not on D2 yet.

    void *malloc(size_t size)
    {
        if (!size)
        {
            return null;
        }

	if (!thread_needLock())
	{
	    return mallocNoSync(size);
	}
	else synchronized (gcLock)
	{
	    return mallocNoSync(size);
	}
    }

Bottom line is, it's mostly just a curiosity/future reference question, since with
a few tweaks, the D version is now *faster* than the C++ version, but how can C++
get away w/ concurrent memory allocations while D can't, or should my C++ version
never have worked in the first place?


More information about the Digitalmars-d-learn mailing list