dev/c/malloc_speed_test/pool_list.c

113 lines
1.6 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;
};
struct block_s pool[MAX_I];
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;
}
#define MAX_B (pool + MAX_I * sizeof(struct block_s))
inline void *alloc()
{
if (!free_pool)
return NULL;
if (busy_pool) {
free_pool->next = busy_pool;
busy_pool->prev = free_pool;
}
else
free_pool->next = NULL;
busy_pool = free_pool;
free_pool = free_pool->next;
return &busy_pool->obj;
}
inline void free(void *p)
{
struct block_s *b1 = (struct block_s *)(p - 2 * sizeof(struct block_s *)),
*b0 = b1->prev,
*b2 = b1->next,
*f1 = free_pool;
// move one busy block to free list
// cut block from free list
if (b0)
b0->next = b2;
if (b2)
b2->prev = b0;
// f1, b1
if (f1) {
b1->next = f1;
f1->prev = b1;
}
else
b1->next = NULL;
// free_pool
free_pool = b2;
// busy_pool
if (busy_pool == b1)
busy_pool = b2;
}
int main()
{
unsigned long long i;
init();
for (i = 0; i < MAX_I; i++)
alloc();
return 0;
}