2005-02-25 12:05:57

by tony osborne

[permalink] [raw]
Subject: why one stack per thread and one heap for all the threads?

Hi,

I wish to be personally CC'ed the answers/comments posted to the list in
response to this post


why in multithreading, each thread has its own stack, but all share the same
heap?
I understand that one stack is needed for each thread as each could have its
own procedure call. but why we don't associate a heap for each thread since
each thread can also create dynamically its own data?


Many thanks

_________________________________________________________________
It's fast, it's easy and it's free. Get MSN Messenger today!
http://www.msn.co.uk/messenger


2005-02-25 20:31:59

by Helge Hafting

[permalink] [raw]
Subject: Re: why one stack per thread and one heap for all the threads?

On Fri, Feb 25, 2005 at 12:03:19PM +0000, tony osborne wrote:
> Hi,
>
> I wish to be personally CC'ed the answers/comments posted to the list in
> response to this post
>
>
> why in multithreading, each thread has its own stack, but all share the
> same heap?
> I understand that one stack is needed for each thread as each could have
> its own procedure call. but why we don't associate a heap for each thread
> since each thread can also create dynamically its own data?
>
>
Because stack memory management is so simple - all memory above the
stack pointer is assumed to be free. (Or below, depending
on which way the stack grows.) You allocate more
simply by incrementing the stack pointer, and free memory by
decrementing it. Such a structure isn�'t trivially shareable!

Heaps on the other hand, have more complex memory management.
You call into a routine, such as malloc() to reserve memory
there. Having several threads doing so simultaneosuly is not
a problem, so there is no need for separate heaps. Separate heaps
would waste memory, as the threads might have very different needs
for memory. Sharing is better, when possible.

If you want separate memory for each thread, consider separate processes
instead.

Helge Hafting