且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C内存池的实现

更新时间:2023-11-13 17:18:22

我觉得优秀的 talloc ,发展成为桑巴舞的一部分,可能是你在找什么。我觉得最有趣的部分是从talloc返回的指针是一个有效的存储环境。他们的例子是:

 结构美孚* X = talloc(mem_ctx,结构foo的);
X->名称= talloc_strdup(X,富);
// ...
talloc_free(X); //释放内存为X和X-GT&;名

在针对您的特定点:

(1)不知道什么防碎裂在这种情况下。在C你不会得到压缩反正垃圾收集,所以我觉得你的选择是比较有限的。

(2)通告比普通的要慢只有4%的malloc(3),这是相当快的。

(3)查看上面的例子。

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

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

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.