0
votes

I know that threads share code/global data but have different stacks. Each thread has its own stack. I believe there is one virtual address space for each process. It means each thread uses this single virtual address space.

I want to know how stack/heap grows in case of multiple threads in the virtual address space? How does OS manages if stack space is full for one thread?

2
On Windows, each thread gets a block of address space for the stack, by default this is 1MB. If the thread overflows this space, the application crashes.Harry Johnston
Note that there are generally 3 parties involved: the OS, the C runtime and your own code. The OS generally doesn't care that your program is written in C and that the C runtime is managing your heap via malloc/free, or that C++ programs use new/delete.MSalters

2 Answers

2
votes

In linux the stack size is determined by guardsize when the guardsize if exceeded the stackoverflow occurs.

It is programmer's responsibility to take care of stackoverflow. The default guardsize value is equal to page size defined in the system.

0
votes

Indeed, the memory manager of your operating system creates a virtual memory space for each process (processes have different memory spaces; threads share the same memory space within a process).

Within the memory space of a thread, each thread has its own stack. However, they share the same heap and clever memory management techniques are used to optimize the shared usage of the stack (see Memory Allocation/Deallocation Bottleneck? as a starting point).

How does OS manages if stack space is full for one thread?

The OS does not manage the stack. The stack is a static data structure created by the compiler. The memory allocations and memory releases from the stack are managed by the compiler, and it knows at any time the size of the stack. Thus, it can split the static memory region of the memory space (i.e. the whole "stack") into thread "sub-stacks".