Where are the stacks for other threads located in the process's virtual address space?

The following figure shows where the process partitions are laid out in the process's virtual address space (on Linux):

enter image description here

You can see that there is only one stack section (since this process only has one thread, which I am assuming).

But what if this process has another thread, where would the stack for that second thread be? will it be located immediately below the first stack?

+3


source to share


2 answers


Empty space for the new thread is created by the parent thread using mmap(MAP_ANONYMOUS|MAP_STACK)

. So they are in the "memory card segment" as your diagram calls it. It can be anywhere it can be large malloc()

. (glibc malloc(3)

uses mmap(MAP_ANONYMOUS)

for large distributions.)

( MAP_STACK

currently not working, and exists in case some future architecture needs special handling).

You are passing a pointer to the new thread stack space to the system callclone(2)

that actually creates the thread. (Try to use strace -f

in a multithreaded process sometime). See also this blog post on thread creation using raw Linux systems .

See this answer on a related question for more details on mmaping files. for example MAP_GROWSDOWN

does not prevent another element from mmap()

choosing an address right below the thread stack, so you cannot depend on it to dynamically grow a small stack the way you can for the main thread of threads (where the kernel reserves the address space even if not mapped yet ).

So even if it mmap(MAP_GROWSDOWN)

was intended for stack allocation, it's so bad that Ulrich Drepper suggested removing it in 2.6.29 .




Also note that the memory-to-map diagram is for a 32-bit kernel. The 64-bit kernel does not need to reserve any user-defined virtual address space to map kernel memory, so a 32-bit process running on an amd64 kernel can use the full 4 GB of virtual address space. (Except for the default low 64k (sysctl vm.mmap_min_addr = 65536

), so dereferencing a NULL pointer does cause an error.)


connected:

See The Relationship Between Stack Limit and Threads for more information on stack size for pthreads. getrlimit(RLIMIT_STACK)

is the main thread stack size. Linux uses pthreads RLIMIT_STACK

as the stack size for new threads.

+4


source


As far as I remember, the space dedicated to the process stack is divided into a smaller part, each of which is used by a given thread. There are also some protective pages to prevent accidental splitting. And yes, the stacks are one below the others ...



-2


source







All Articles