dev/c/malloc_speed_test/pool_list.c

118 lines
1.7 KiB
C

#include <stdlib.h>
#include <stdio.h>
#define MAX_I 0x00ffffff
#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;
};
static struct block_s pool[MAX_I];
static struct block_s *free_pool = NULL,
*busy_pool = NULL;
/*
* инициализация пула
*/
void init()
{
size_t i;
size_t max_i = MAX_I - 1;
for (i = 1; i < max_i; i++) {
pool[i].prev = &pool[i - 1];
pool[i].next = &pool[i + 1];
}
pool[0].prev = NULL;
pool[0].next = &pool[1];
pool[MAX_I - 1].prev = &pool[MAX_I - 2];
pool[MAX_I - 1].next = NULL;
free_pool = &pool[0];
busy_pool = NULL;
}
inline void *pool_alloc()
{
if (!free_pool)
return NULL;
free_pool->prev = free_pool->next; // save free_pool->next in free_pool->prev
free_pool->next = busy_pool;
if (busy_pool)
busy_pool->prev = free_pool;
busy_pool = free_pool;
free_pool = free_pool->prev;
busy_pool->prev = NULL; // saved in free_pool->prev to NULL
return &busy_pool->obj;
}
inline void pool_free(void *p)
{
if (!p)
return;
struct block_s *b1 = (struct block_s *)(p - 2 * sizeof(struct block_s *)),
*b0 = b1->prev,
*b2 = b1->next;
if (b0)
b0->next = b2;
if (b2)
b2->prev = b0;
if (free_pool) {
b1->next = free_pool;
free_pool->prev = b1;
}
else
b1->next = NULL;
free_pool = b2;
if (busy_pool == b1)
busy_pool = b2;
}
void *mem[MAX_I];
int main()
{
unsigned long long i;
init();
for (i = 0; i < MAX_I; i++)
if (!(mem[i] = pool_alloc())) {
printf("не удалось выделить память под %lld блок\n", i);
break;
}
for (i = 0; i < MAX_I; i++)
pool_free(mem[i]);
return 0;
}