Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address Space Layout for a Multithreaded Linux Process

I want to know the full detail of the address space layout of a multithreaded Linux Process for both 64 bit and 32 bit. Link to any article that describes it will be appreciated. And note that I need to know full details, not just an overview, because I will be directly dealing with it. So I need to know for example, where are the thread stacks located, the heap, thread private data etc...

like image 794
MetallicPriest Avatar asked Jul 06 '11 10:07

MetallicPriest


People also ask

Does thread share same address space?

Threads are sometimes called lightweight processes because they have their own stack but can access shared data. Because threads share the same address space as the process and other threads within the process, the operational cost of communication between the threads is low, which is an advantage.

What is address space of a thread?

An address space is simply the mapping of logical addresses to specific pieces of physical memory. So when we say that all the threads in a process share the same address space we mean that when accessing a variable foo in global scope all the threads will see the same variable.

Do threads share the same stack space?

Note: stack and registers can't be shared among the threads. Each thread has its own stack and registers.

Where is thread stack memory located?

Stack space for a new thread is created by the parent thread with mmap(MAP_ANONYMOUS|MAP_STACK) . So they're in the "memory map segment", as your diagram labels it. It can end up anywhere that a large malloc() could go.


1 Answers

Thread stacks are allocated with mmap at thread start (or even before - you can set the stack space in pthread_attrs). TLS data is stored in the beginning of thread's stack. Size of thread's stacks is fixed, typically it is from 2 to 8 MB. Stack size of each thread can't be changed while the thread is live. (First thread - running main - is still uses main stack at the end of address space and this stack may grow and shrink.) Heap and code is shared between all threads. Mutexes can be anywhere in data section - it is just a struct.

The mmap of thread's stack is not fixed at any address:

Glibc sources

 mem = mmap (NULL, size, prot,
                  MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);

PS modern GCC allows threads stack to be unlimited with SplitStacks feature

like image 80
osgx Avatar answered Oct 20 '22 10:10

osgx