为什么堆栈内存大小如此有限? [英] why is stack memory size so limited?

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

问题描述

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

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

更新:我的意图可能不清楚,我不想在堆栈上分配巨大的对象,我不需要更大的堆栈.这个问题纯属好奇.

解决方案

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

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

一个有趣的问题是,为什么我们在 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天全站免登陆