什么是内存池

178 阅读2分钟

概念

内存池,是使用池进行内存管理,允许动态分配固定大小的内存块。

将内存池和malloc和C++的new运算符相比教,后者由于块大小可变而导致碎片化,由于性能原因不建议在实时系统中使用。一种更有效的解决方案是预分配多个具有相同大小的内存块,称为内存池。 应用程序可以在运行时分配,访问和释放由句柄表示的内存块。

一些系统,例如Web服务器Nginx,使用术语“内存池”来指代一组可变大小的分配,这些分配的内存以后可以一次性全部释放。

Any kind of "pool" is really just resources you've acquired/initialized in advance so that they're already ready to go, not allocated on the fly with each client request. When clients finish using them, the resource returns to the pool instead of being destroyed.

Memory pools are basically just memory you've allocated in advance (and typically in big blocks). For example, you might allocate 4 kilobytes of memory in advance. When a client requests 64 bytes of memory, you just hand them a pointer to an unused space in that memory pool for them to read and write whatever they want. When the client is done, you can just mark that section of memory as being unused again.

简单的内存池实现

一个简单的内存池模块可以在编译时分配三个池。应用程序可以通过以下接口分配,访问和释放内存:

从池中分配内存。该函数将确定所需块所在的池。如果该池的所有块都已保留,则该函数将尝试在下一个更大的池中找到一个。

获取对分配的内存的访问指针。

释放以前分配的内存块。

Memory pool vs malloc

  • 优点:

内存池中成千上万个对象的内存释放只是一个操作,如果使用malloc为每个对象分配内存,则需要一个接一个地释放。

可以将内存池分为分层的树状结构,这适用于特殊的编程结构,例如循环和递归。

固定大小的块内存池不需要为每个分配存储元数据(诸如已分配块大小之类的)。特别是对于小块分配,这可以节省大量空间。

保证了实时系统上的确定性行为,避免出现内存不足错误。

  • 缺点:

内存池可能需要为部署它们的应用程序进行调整。

本文参考资料

[1] Memory pool

en.wikipedia.org/wiki/Memory…

[2] What are the usual im­ple­men­ta­tion de­tails be­hind mem­ory pools?

stackoverflow.com/questions/3…