[fpc-pascal] a few more heap questions
sethdgrover at gmail.com
Wed Sep 8 18:08:41 CEST 2010
A while ago I asked a question on this list:
>> 3. When this thread exits (in the example of using BeginThread, when
>> the TThreadFunc function passed in to BeginThread terminates) the heap
>> for that thread, in addition to the other threadvars, are
>> automatically disposed, correct?
To which Jonas replied, helpfully:
> Only the already freed blocks that are still around are automatically disposed, because allocated blocks
> may still be referenced by other threads. The memory reserved for holding
> threadvars is indeed freed.
I need to understand a few more things... I'm still a little confused
at how this works. I've read heap.inc and cthreads.pp but I'm still a
little fuzzy on a few details...
In heap.inc, the "freelists" variable which represents the heap, is a
threadvar. So when GetMem is called, it works its way down into
SysGetMem_Fixed and uses the heap for that thread to get the memory.
This makes sense to me.
What I'm still a little unsure on is what happens to the heap when the
thread exits. If the heap itself (freelists) is a threadvar, how is
the statement "Only the already freed blocks that are still around are
automatically disposed, because allocated blocks may still be
referenced by other threads" accomplished? Are any still-allocated
blocks belonging to that heap relocated to be managed by some other
heap so that they can be used and/or tracked (by heaptrc, for
example)? I think my reading of FinalizeHeap in heap.inc, called by
DoneThread in thread.inc indicates this.
So in other words, here's what I *think* is happening, please tell me
if I'm correct:
- when a thread is started, InitHeapThread in heap.inc is called by
InitThread in thread.inc, which initializes that thread's freelists
- the thread runs, all GetMem/FreeMem calls in that thread use that
- when the thread exists, FinalizeHeap in heap.inc is called by
DoneThread in thread.inc. If there are any chunks still allocated on
that heap then those blocks are reassigned to the orphaned_freelists
heap (which is global across all threads) so that that memory can
still be used by other threads and so that something like heaptrc
would still work to catch those blocks.
- then, once any remaining blocks of freelists are no longer managed
by freelists, ReleaseThreadVars is called to actually free the memory
associated with the threadvar itself
Is that correct?
This email is fiction. Any resemblance to actual events
or persons living or dead is purely coincidental.
More information about the fpc-pascal