加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

如何在Linux中的相同进程下为线程分配堆栈或内存

发布时间:2020-12-14 01:05:18 所属栏目:Linux 来源:网络整理
导读:对于正常的函数调用,将创建堆栈帧并将其存储在堆栈中.但 如何在一个进程内为两个线程分配内存,以及在线程调用其他函数时如何处理堆栈帧. 解决方法 Linux中当前的“线程”概念是 NPTL. NPTL使用 clone() ,包装 sys_clone() .为新的’线程’分配堆栈在用户空间
对于正常的函数调用,将创建堆栈帧并将其存储在堆栈中.但
如何在一个进程内为两个线程分配内存,以及在线程调用其他函数时如何处理堆栈帧.

解决方法

Linux中当前的“线程”概念是 NPTL. NPTL使用 clone(),包装 sys_clone().为新的’线程’分配堆栈在用户空间(即libc)中处理,而不是在内核(即Linux)中处理.库可以使用选择分配(例如malloc)分配堆栈,然后调用clone()将此地址作为堆栈传递(当然,需要传递分配区域的顶部,因为堆栈在大多数平台上向下增长) :

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,但最后只是在用户空间中分配的内存区域.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读