C ++中mutithreaded进程的内存布局(memory layout of multithreaded process in C++)

编程入门 行业动态 更新时间:2024-10-21 15:41:43
C ++中mutithreaded进程的内存布局(memory layout of multithreaded process in C++)

我对在多线程进程中如何排列堆栈和堆有点困惑: 1)每个线程都有自己的私有堆栈。 2)所有线程共享堆 3)当程序动态创建线程(例如Java中的新Thread())时,该对象在堆上分配。

那么堆是否包含线程对象的内存,这意味着堆包含堆栈(属于线程)?

Am a bit confused on how stack and heap are arranged in multithreaded processes:

Each thread has its own private stack. All threads share the heap When the program dynamically creates thread (ex: new Thread() in Java), the object is allocated on heap.

so does the heap contain memory for thread object, which means does heap contains stack (belonging to threads)?

最满意答案

它的含糊不清,因为我们不想约束线程软件的实现者。

每个线程都有自己的私有堆栈。

由于每个线程执行一组函数互为独立,因此需要存储返回地址等,因此每个线程都需要自己的堆栈。

所有线程共享堆

这是实现它的最简单方法。 这也意味着所有线程共享一个共同的内存块,这样每个线程只需通过修改内存就可以与其他线程通信。

当程序动态创建线程(例如Java中的新线程()时),该对象在堆上分配。

您在问题1中提到的堆栈。我们需要为它保留内存。 所以我们分配一大块的堆给它给线程并说使用这块内存来实现你的堆栈。 (并不是说它是这样做的,但这是一种简单的技术)。

那么堆是否包含线程对象的内存,这意味着堆包含堆栈(属于线程)?

在单线程程序中,有空间将堆栈实现为堆的块。 堆栈和堆的概念是分开的并且相互增长就是这样的; 一个概念。 未定义如何实现它们并且它们不是我们无法在堆内实现堆栈的原因。 有关更多信息,请参阅此问题: 堆栈增长方向

Its delibrately vague as we don;t want to constrain the implementers of the threading software.

Each thread has its own private stack.

As each thread executes a set of function independ from each other they need to store return addresses etc thus each needs its own stack.

All threads share the heap

That's the easiest way to implement it. This also means that all the threads share a common chunk of memory so that each thread can communicate with other threads simply by modifying memory.

When the program dynamically creates thread (ex: new Thread() in Java), the object is allocated on heap.

The stack you mention in question 1. We need to reserve memory for it. So we allocate a chunk of the heap give it to the thread and say use this chunk of memory to implement your stack. (Not saying that it does it this way but that is a simple technique for doing it).

so does the heap contain memory for thread object, which means does heap contains stack (belonging to threads) ?

In a single threaded program there is room to implement the stack as chunks of the heap. The concept of stack and heap being separate and growing towards each other is just that; a concept. It is undefined how either are implemented and their is no reason that we can not implement the stack inside the heap. See this question for more information: stack growth direction

更多推荐

本文发布于:2023-08-07 21:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布局   进程   内存   mutithreaded   process

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!