C 中的内存池实现

发布于 2024-11-29 16:45:29 字数 150 浏览 1 评论 0原文

我正在寻找一个好的 C 内存池实现。

它应该包括以下内容:

  1. 反碎片。
  2. 速度超级快:)
  3. 能够在某个标识符下“捆绑”不同大小的多个分配,并删除具有给定标识符的所有分配。
  4. 线程安全

I am looking for a good memory pool implementation in C.

it should include the following:

  1. Anti fragmentation.
  2. Be super fast :)
  3. Ability to "bundle" several allocations from different sizes under some identifier and delete all the allocations with the given identifier.
  4. Thread safe

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

柠檬心 2024-12-06 16:45:29

我认为作为 samba 的一部分开发的优秀 talloc 可能是你在寻找什么。我发现最有趣的部分是从talloc 返回的任何指针都是有效的内存上下文。他们的例子是:

struct foo *X = talloc(mem_ctx, struct foo);
X->name = talloc_strdup(X, "foo");
// ...
talloc_free(X); // frees memory for both X and X->name

针对您的具体观点:

(1)不确定在这种情况下什么是反碎片。在 C 中,无论如何你都不会得到压缩垃圾收集,所以我认为你的选择有些有限。

(2) 它宣称只比普通的 malloc(3) 慢 4%,相当快。

(3) 参见上面的例子。

(4) 只要不同的线程使用不同的上下文,它就是线程安全的。底层的 malloc 是线程安全的。

I think the excellent talloc, developed as part of samba might be what you're looking for. The part I find most interesting is that any pointer returned from talloc is a valid memory context. Their example is:

struct foo *X = talloc(mem_ctx, struct foo);
X->name = talloc_strdup(X, "foo");
// ...
talloc_free(X); // frees memory for both X and X->name

In response to your particular points:

(1) Not sure what anti-fragmentation is in this case. In C you're not going to get compacting garbage collection anyway, so I think your choices are somewhat limited.

(2) It advertises being only 4% slower than plain malloc(3), which is quite fast.

(3) See example above.

(4) It is thread safe as long as different threads use different contexts & the underlying malloc is thread safe.

各自安好 2024-12-06 16:45:29

您是否研究过

两者都利用内存池,但保持其大部分透明用户。

一般来说,您会在自己的自定义内存池中找到最佳性能(您可以针对您的模式进行优化)。我最终为不同的访问模式编写了一些。

Have you looked into

Both leverage a memory pool but keep it mostly transparent to the user.

In general, you will find best performance in your own custom memory pool (you can optimize for your pattern). I ended up writing a few for different access patterns.

深爱不及久伴 2024-12-06 16:45:29

对于经过彻底尝试和测试的内存池,您可能只想使用 APR 内存池:

http://apr.apache.org/docs/apr/1.4/apr__pools_8h.html

请注意,单个池不是线程安全的,您必须自己处理。

For memory pools that have been thoroughly tried and tested you may want to just use the APR ones:

http://apr.apache.org/docs/apr/1.4/apr__pools_8h.html

Mind you, single pools are not thread safe, you'll have to handle that yourself.

说好的呢 2024-12-06 16:45:29

bget 是另一种选择。它经过充分测试并准备好投入生产。

http://www.fourmilab.ch/bget/

bget is another choice. It's well tested and production ready.

http://www.fourmilab.ch/bget/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文