1

A program's runtime stack is stored as part of virtual memory, and starts at address X on system Y (not taking into account randomization). When a new thread is created, with its own independent stack, where is it stored? (threads share their virtual memory)

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Edward Garemo
  • 434
  • 3
  • 13
  • Please edit your question. It does not specify the context, so it is impossible to provide the answer. For example, add "64-bit Microsoft Windows process", if this is the case. – Maxim Masiutin Jan 08 '20 at 16:27
  • 4
    As a generic answer, the stack for a new thread can potentially be placed pretty much anywhere in the process address space, and that’d be decided by the library/software providing the thread implementation (most likely in cooperation with the operating system). For Linux/pthreads, answers to the following question contain many more details: https://stackoverflow.com/questions/44858528. – Dato Jan 09 '20 at 01:47

1 Answers1

0

Almost every threading libraries lets you specify the stack size:

HANDLE CreateThread(
  LPSECURITY_ATTRIBUTES   lpThreadAttributes,
  SIZE_T                  dwStackSize,
  LPTHREAD_START_ROUTINE  lpStartAddress,
  __drv_aliasesMem LPVOID lpParameter,
  DWORD                   dwCreationFlags,
  LPDWORD                 lpThreadId
);
uintptr_t _beginthread( // NATIVE CODE
   void( __cdecl *start_address )( void * ),
   unsigned stack_size,
   void *arglist
);
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Before the thread starts, the operating system allocates memory (just like malloc) for the new thread to execute. Some systems also provide gaps ("guard pages") so that the stacks won't collide with each other. Where they are stored are platform-dependent, but generally subsequent threads' stacks may be allocated in a different region than the main thread. For Linux this is handled by the C library and uses plain mmap to allocate them AFAIK.

Jin-oh Kang
  • 317
  • 1
  • 8