c - linux同进程下的线程如何分配stack或内存

标签 c linux memory process stack

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

最佳答案

Linux 中当前的“线程”概念是NPTL。一。 NPTL 使用 clone() , 它包装了 sys_clone() .为新“线程”分配堆栈是在用户空间(即 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 , 但最后只是在用户空间分配的内存区域。

关于c - linux同进程下的线程如何分配stack或内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28535838/

相关文章:

linux - Debian 启动脚本无法启动

c - 适当的内存分配

c - 访问冲突 strcpy

导航链表时无法访问指针

c - C 语言编程中的图形

c - 无法将完整脚本写入串行端口上的设备

使用gcc在C中将float转换为unsigned int

linux - 无法找到包 Node 遗留

c++ - 如何在linux数据类型中定义#define S64_MIN?

c - C 编程中的堆和栈