пул переделан под любую структуру объекта

This commit is contained in:
Kolan Sh 2011-04-30 23:18:13 +04:00
parent 056ad46082
commit cb4a83aba3
2 changed files with 21 additions and 16 deletions

View File

@ -8,12 +8,12 @@
struct block_s {
struct block_s *next;
struct block_s *prev;
char obj[1];
char obj;
};
struct block_pool {
size_t nblocks;
struct block_s *pool;
void *pool;
struct block_s *free_pool;
struct block_s *busy_pool;
};
@ -21,27 +21,32 @@ struct block_pool {
/*
* инициализация пула
*/
void pool_init(struct block_pool *bp, size_t nblocks)
void pool_init(struct block_pool *bp, size_t nblocks, size_t block_size)
{
size_t i;
bp->nblocks = nblocks;
bp->pool = (struct block_s *)malloc(nblocks * sizeof(struct block_s));
block_size += 2 * 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 = (struct block_s *)malloc(nblocks * block_size);
void *p = bp->pool + block_size,
*pmax = p + (nblocks - 2) * block_size;
for ( ; p < pmax; p += block_size) {
((struct block_s *)p)->prev = (struct block_s *)(p - block_size);
((struct block_s *)p)->next = (struct block_s *)(p + block_size);
}
bp->pool[0].prev = NULL;
bp->pool[0].next = &bp->pool[1];
((struct block_s *)bp->pool)->prev = NULL;
((struct block_s *)bp->pool)->next = (struct block_s *)(bp->pool + block_size);
bp->pool[nblocks - 1].prev = &bp->pool[nblocks - 2];
bp->pool[nblocks - 1].next = NULL;
((struct block_s *)(bp->pool + (nblocks - 1) * block_size))->prev =
(struct block_s *)(bp->pool + (nblocks - 2) * block_size);
((struct block_s *)(bp->pool + (nblocks - 1) * block_size))->next = NULL;
bp->free_pool = &bp->pool[0];
bp->free_pool = (struct block_s *)bp->pool;
bp->busy_pool = NULL;
}
@ -121,7 +126,7 @@ int main()
size_t nblocks = 0xffffff;
pool_init(&bp, nblocks);
pool_init(&bp, nblocks, sizeof(struct object_s));
void **mem = malloc(nblocks * sizeof(void *));
@ -130,7 +135,7 @@ int main()
printf("не удалось выделить память под %lld блок\n", i);
break;
}
return 0;
for (i = 0; i < nblocks; i++)
pool_free(&bp, mem[i]);

View File

@ -9,5 +9,5 @@ c++ -O2 vector_add.cpp -o vector_add && time ./vector_add
echo -e "\n\npool1.c test:"
cc -O2 pool1.c -o pool1 && time ./pool1
echo -e "\n\npool_list.c test (вычесть 279мс на init()):"
echo -e "\n\npool_list.c test (вычесть 121мс на init()):"
cc -O2 pool_list.c -o pool_list && time ./pool_list