Linux同进程下的线程如何分配Stack或内存

How Stack or memory is allocated for threads under the same process in Linux

对于正常的函数调用,创建堆栈帧并将其存储在堆栈中。但是
如何在一个进程中为两个线程分配内存,以及当线程调用其他函数时如何处理堆栈帧。

正如有人评论的那样,每个线程都有自己的堆栈。当从该线程调用函数时,将在该堆栈中创建新的堆栈框架。

Linux 中的当前 'thread' 概念是 NPTL one. NPTL uses clone(), which wraps sys_clone()。为新 'thread' 分配堆栈是在用户 space(即 libc)中处理的,而不是在内核(即 Linux)中处理的。库可以使用选择分配(例如 malloc)分配一个堆栈,然后调用 clone() 传递这个地址作为堆栈(当然,需要传递分配的 top区域,因为堆栈在大多数平台上向下增长):

Unlike fork(2), clone() allows the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. ...

The main use of clone() is to implement threads: multiple threads of control in a program that run concurrently in a shared memory space.

When the child process is created with clone(), it executes the function fn(arg) ...

The child_stack argument specifies the location of the stack used by the child process ...

如果您想了解更多具体细节,请打开您的发行版 pthread_create 实现的源代码并阅读。

例如pthread_create.c:

int
__pthread_create_2_1 (newthread, attr, start_routine, arg)
  ...
  struct pthread *pd = NULL;
  int err = ALLOCATE_STACK (iattr, &pd);
  ...

allocatestack.c:

 # define ALLOCATE_STACK(attr, pd) allocate_stack (attr, pd, &stackaddr)

 static int
 allocate_stack (const struct pthread_attr *attr, struct pthread **pdp,
    ALLOCATE_STACK_PARMS)
 ...

你会看到堆栈分配有一些好处,比如缓存和重用堆栈区域,guard pages,但最终只是分配给用户的内存区域 space。