dev/c/malloc_speed_test/pool_list.c

127 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;
};
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;
struct block_s *f1 = free_pool,
*f2 = free_pool->next,
*b1 = busy_pool;
// move one free block to busy list
// f1, b1
if (b1) {
f1->next = b1;
b1->prev = f1;
}
else
f1->next = NULL;
// f2
if (f2)
f2->prev = NULL;
// free_pool
free_pool = f2;
// busy_pool
busy_pool = f1;
return &f1->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;
}