How does the OS implement or maintain a stack for each thread?

There were various questions on SO about whether streams get their own stack. However, I do not understand how the OS is implemented or how the OS usually implements one stack per thread. In OS books, the program memory layout is displayed as follows:

Memory layout

Please note that this can be considered as a continuous block of memory (virtual memory). I would suggest that part of the virtual memory is split between stacks for threads. This brings me to the second part of this question: a popular question about a technical interview involves trying to implement 3 stacks using a single array. Is this problem directly related to the decision to implement thread stacks?

I summarize my questions this way:

  • How does a modern OS work, say, Linux shares memory space for stacks of different threads?
  • Is "3 stacks using 1 array" directly related or responsible for the above question?

PS: It might be better to explain the images in order to explain how the memory is divided for different stacks of threads.

+5
source share
2 answers

The image shown above is completely out of date for both Windows and Linux. At which addresses the individual distributions do not matter. The virtual address space is large at 32 bits and huge at 64 bits. The OS just needs to cut out part of it somewhere and pass it on.

Each stack is an independent allocation of virtual memory , which can be placed in arbitrary places. It is important to note that stacks are usually finite in size . The OS reserves a certain maximum size (for example, 1 MB or 8 MB). The stack cannot exceed this size. This is offered differently in the (obsolete) image above. The stack does grow, but when the fixed space is exhausted, the stack overflows. In practice, this is not a problem. In fact, exceeding a reasonable stack size is considered a mistake.

Binary images (above: text, initialized data and bss) are also placed anywhere. They are also fixed in size.

a heap consists of several segments. It can grow arbitrarily by simply adding more segments. The heap is managed by user-mode libraries. The kernel does not know about this. The entire core is the provision of virtual memory slabs at select locations.

+2
source

1) A thread stack is just an adjacent block in virtual memory. The maximum size is fixed. It might look like this:
thdcontext.jpg

2) I do not think that this is directly related to this problem, since the limitation of the size of the stack stack is known when creating the thread, but nothing is known about each of the three stack sizes in the "3 stacks using 1 array" problem.

+1
source

Source: https://habr.com/ru/post/1200253/


All Articles