且构网

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

实现自己的内存池

更新时间:2023-11-13 17:31:28

如果您希望能够内存返回到池中,它变得更加复杂。然而,对于快速和不相当那么脏的方法,你可能想实现一些code,你可以再次使用...

If you want to be able to return memory to the pool, it gets more complicated. However, for the quick and not-quite-so-dirty approach, you may want to implement some code that you can use again...

typedef struct pool
{
  char * next;
  char * end;
} POOL;

POOL * pool_create( size_t size ) {
    POOL * p = (POOL*)malloc( size + sizeof(POOL) );
    p->next = (char*)&p[1];
    p->end = p->next + size;
    return p;
}

void pool_destroy( POOL *p ) {
    free(p);
}

size_t pool_available( POOL *p ) {
    return p->end - p->next;
}

void * pool_alloc( POOL *p, size_t size ) {
    if( pool_available(p) < size ) return NULL;
    void *mem = (void*)p->next;
    p->next += size;
    return mem;
}

在我的经验,使用这样池的时候,分配许多对象,我想precalculate如何将需要的内存,这样我不浪费,但我也不想犯任何错误(喜欢不分配enoudh)。所以,我把所有的拨款code在循环中,并设置了我的池分配函数接受执行对空游泳池的虚拟分配的标志。周围循环的第二次,我已经计算出池的大小,所以我可以创建池并做真正的分配都具有相同的函数调用和没有重复code。你需要改变我的建议的池code,因为你不能做到这一点与指针算法,如果内存尚未分配。

In my experience, when using pools like this to allocate many objects, I want to precalculate how much memory will be needed so that I'm not wasteful, but I also don't want to make any mistakes (like not allocating enoudh). So I put all the allocation code inside a loop, and set up my pool allocation functions to accept a flag that performs a 'dummy' allocation on an empty pool. The second time around the loop, I have already calculated the size of the pool so I can create the pool and do the real allocations all with the same function calls and no duplicate code. You'd need to change my suggested pool code, because you can't do this with pointer arithmetic if the memory hasn't been allocated.