StackThreads and Phobos

mclysenk at mtu.edu mclysenk at mtu.edu
Mon Jul 3 06:47:32 PDT 2006


In article <e8artd$16e0$1 at digitaldaemon.com>, Bruno Medeiros says...
>
>Unless my understanding of this is wrong, the use of the word "never" 
>(gets collected) is too strong. If during normal program flow the stack 
>is overwritten again, the reference becomes free. Or am I missing something?
>Also, doesn't this happen with any regular function?
>

Well, you are correct, that it may still get collected in the future -
regardless, its prospects are fairly dim.  You are also right in your statement
that this is not abnormal behavior for functions, and the GC knows this.  It has
a special case which handles the stack of a regular function.

When the GC does a full collect, it pauses all threads and marks the range from
the stack pointer to the bottom of the stack.  This prevents it from scanning
stuff which is no longer valid, since that range never gets marked.  This works
very well.

The bad part happens when we create multiple stacks for one thread.  In order
for the GC to properly scan them, we need to mark their stack when it is not in
use.  If the GC didn't scan their stack, then we'd accidentally over-collect
stuff they were using.  If we mark the entire stack range, then we'd
under-collect and get a bunch of memory leaks.  To fix this, we use addRange to
mark the active part of their stack before we switch out their context, and
removeRange to delete their old - and potentially invalid - stack range when we
switch into their context.

This part is tricky, and it burned me many times while I was working on stack
threads before I finally caught on.  It is not a big deal to fix once you know
what's happening.  The main disadvantage at the moment is removeRange - it's
just too slow!  It can be fixed, but it requires changing phobos.  

-Mikola Lysenko





More information about the Digitalmars-d mailing list