dev/c/malloc_speed_test/pool_list.c

135 lines
2.3 KiB
C
Raw Normal View History

#include <stdlib.h>
#include <stdio.h>
#define bool char
#define TRUE 1
#define FALSE 0
struct object_s {
char val;
};
struct block_s {
struct block_s *next;
struct block_s *prev;
struct object_s obj;
};
struct block_pool {
size_t nblocks;
struct block_s *pool;
struct block_s *free_pool;
struct block_s *busy_pool;
};
/*
* инициализация пула
*/
void pool_init(struct block_pool *bp, size_t nblocks)
{
size_t i;
bp->nblocks = nblocks;
bp->pool = (struct block_s *)malloc(nblocks * sizeof(struct block_s));
size_t max_i = nblocks - 1;
for (i = 1; i < max_i; i++) {
bp->pool[i].prev = &bp->pool[i - 1];
bp->pool[i].next = &bp->pool[i + 1];
}
bp->pool[0].prev = NULL;
bp->pool[0].next = &bp->pool[1];
bp->pool[nblocks - 1].prev = &bp->pool[nblocks - 2];
bp->pool[nblocks - 1].next = NULL;
bp->free_pool = &bp->pool[0];
bp->busy_pool = NULL;
}
void pool_destroy(struct block_pool *bp)
{
free(bp->pool);
bp->nblocks = 0;
bp->pool = bp->free_pool = bp->busy_pool = NULL;
}
inline void *pool_alloc(struct block_pool *bp)
{
if (!bp->free_pool)
return NULL;
bp->free_pool->prev = bp->free_pool->next; // save free_pool->next in free_pool->prev
bp->free_pool->next = bp->busy_pool;
if (bp->busy_pool)
bp->busy_pool->prev = bp->free_pool;
bp->busy_pool = bp->free_pool;
bp->free_pool = bp->free_pool->prev;
bp->busy_pool->prev = NULL; // saved in free_pool->prev to NULL
return &bp->busy_pool->obj;
}
inline void pool_free(struct block_pool *bp, void *p)
{
if (!p)
return;
struct block_s *b1 = (struct block_s *)(p - 2 * sizeof(struct block_s *)),
2011-04-29 22:18:10 +04:00
*b2 = b1->next;
2011-04-29 22:19:07 +04:00
if (b1->prev)
b1->prev->next = b2;
if (b2)
2011-04-29 22:19:07 +04:00
b2->prev = b1->prev;
if (bp->free_pool) {
b1->next = bp->free_pool;
bp->free_pool->prev = b1;
}
else
b1->next = NULL;
bp->free_pool = b2;
if (bp->busy_pool == b1)
bp->busy_pool = b2;
}
int main()
{
unsigned long long i;
struct block_pool bp;
size_t nblocks = 0xffffff;
pool_init(&bp, nblocks);
void **mem = malloc(nblocks * sizeof(void *));
for (i = 0; i < nblocks; i++)
if (!(mem[i] = pool_alloc(&bp))) {
printf("не удалось выделить память под %lld блок\n", i);
break;
}
for (i = 0; i < nblocks; i++)
pool_free(&bp, mem[i]);
free(mem);
pool_destroy(&bp);
return 0;
}