为什么栈的内存大小这么有限呢? [英] why is stack memory size so limited?

查看:238
本文介绍了为什么栈的内存大小这么有限呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在堆上分配内存时,唯一的限制是可用RAM(或虚拟内存)。它使Gb的内存。



那么为什么堆栈大小如此有限(大约1 Mb)?什么技术原因阻止您在堆栈上创建真正大的对象?



更新:我的意图可能不清楚,不想要在堆栈上分配巨大的对象,并且不需要更大的堆栈。这个问题只是纯粹的好奇心。

解决方案

我的直觉如下。堆栈不像堆那样容易管理。堆栈需要存储在连续的内存位置。这意味着您不能根据需要随机分配堆栈,但您至少需要为此目的预留虚拟地址。保留的虚拟地址空间的大小越大,可以创建的线程越少。



例如,32位应用程序通常具有2GB的虚拟地址空间。这意味着如果堆栈大小为2MB(在pthreads中为默认值),则最多可以创建1024个线程。这对于诸如Web服务器的应用程序可能很小。将堆栈大小增加到例如100MB(即,保留100MB,但不一定立即将100MB分配给堆栈)将将线程数限制为约20,这甚至对于简单的GUI应用也是有限的。 p>

一个有趣的问题是,为什么我们在64位平台上仍然有这个限制。我不知道答案,但我假设人们已经习惯了一些堆栈最佳实践:小心在堆上分配巨大的对象,如果需要,手动增加堆栈大小。因此,没有人发现在64位平台上添加巨大堆栈支持是有用的。


When you allocate memory on the heap, the only limit is free RAM (or virtual memory). It makes Gb of memory.

So why is stack size so limited (around 1 Mb) ? What technical reason prevents you to create really big objects on the stack ?

Update : My intent might not be clear, I do not want to allocate huge objects on the stack and I do not need a bigger stack. This question is just pure curiosity.

解决方案

My intuition is the following. The stack is not as easy to manage as the heap. The stack need to be stored in continuous memory locations. This means that you cannot randomly allocate the stack as needed, but you need to at least reserve virtual addresses for that purpose. The larger the size of the reserved virtual address space, the fewer threads you can create.

For example, a 32-bit application generally has a virtual address space of 2GB. This means that if the stack size is 2MB (as default in pthreads), then you can create a maximum of 1024 threads. This can be small for applications such as web servers. Increasing the stack size to, say, 100MB (i.e., you reserve 100MB, but do not necessarily allocated 100MB to the stack immediately), would limit the number of threads to about 20, which can be limiting even for simple GUI applications.

A interesting question is, why do we still have this limit on 64-bit platforms. I do not know the answer, but I assume that people are already used to some "stack best practices": be careful to allocate huge objects on the heap and, if needed, manually increase the stack size. Therefore, nobody found it useful to add "huge" stack support on 64-bit platforms.

这篇关于为什么栈的内存大小这么有限呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆