dev/c/malloc_speed_test/pool_list.c

119 lines
1.8 KiB
C
Raw Normal View History

#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 *)),
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;
2011-04-29 22:18:10 +04:00
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;
}
int main()
{
unsigned long long i;
init();
void **mem = malloc(MAX_I * sizeof(void *));
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]);
free(mem);
return 0;
}