GC + malloc/free = deadlock

Steven Schveighoffer schveiguy at yahoo.com
Mon Apr 23 04:57:20 PDT 2012


On Mon, 23 Apr 2012 02:41:21 -0400, Benjamin Thaut  
<code at benjamin-thaut.de> wrote:

> I wrote a small "bad example" program for a presentation. It calls  
> malloc/free very frequently and I wanted to profile the impact of this  
> compared to a pool allocator solution. Unfortunately I had to notice  
> that the program only runs for a fraction of a second before  
> deadlocking. As it seems the following situation accurs:
>
> 1) Thread 1 calls malloc(), and locks the internal malloc mutex
> 2) Thread 2 triggers garbage collection and stops thread 1
> 3) Thread 2 is done collecting garbage and calls all destructors. One of  
> these calls free(), as the malloc mutex is still locked by Thread 1 and  
> Thread 1 will never release the mutex, as it is stoped, Thread 2  
> deadlocks.

This shouldn't happen.  The collection routine is specifically designed to  
avoid this.  I remember when Sean put it into Tango after an IRC  
conversation.

The correct sequence is:

1. stop the world
2. Perform mark on all data (identifying which blocks should be freed)
3. resume the world
4. Call dtors on unreferenced data and deallocate.

This was to fix the exact problem you are having, albeit the malloc/free  
were indirect by calls to C-libs.

Please file a bug.

-Steve


More information about the Digitalmars-d mailing list