Am a bit confused on how stack and heap are arranged in multithreaded processes:
- Each thread has its own private stack.
- All threads share the heap
- When the program dynamically creates thread (ex: new Thread() in Java), the object is allocated on heap.
so does the heap contain memory for thread object, which means does heap contains stack (belonging to threads)?
Its delibrately vague as we don;t want to constrain the implementers of the threading software.
As each thread executes a set of function independ from each other they need to store return addresses etc thus each needs its own stack.
That’s the easiest way to implement it. This also means that all the threads share a common chunk of memory so that each thread can communicate with other threads simply by modifying memory.
The stack you mention in question 1. We need to reserve memory for it. So we allocate a chunk of the heap give it to the thread and say use this chunk of memory to implement your stack. (Not saying that it does it this way but that is a simple technique for doing it).
In a single threaded program there is room to implement the stack as chunks of the heap. The concept of stack and heap being separate and growing towards each other is just that; a concept. It is undefined how either are implemented and their is no reason that we can not implement the stack inside the heap. See this question for more information: stack growth direction