-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmempool.c
45 lines (37 loc) · 1020 Bytes
/
mempool.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdlib.h>
#include "mempool.h"
void mempool_init(mempool_instance *mempool, unsigned int obj_size, unsigned int pool_size)
{
void *block;
int i;
/* Block: [Header, data]
* Memory pool: [Block.0, Block.1, Block.2, ..., Block.pool_size-1]
*/
/* In the future it could use mmap() instead malloc() */
mempool->pool = malloc((sizeof(mempool_block_header) + obj_size) * pool_size);
DLIST_INIT(mempool);
for(block = mempool->pool, i = 0; i < pool_size; i++) {
DLIST_APPEND(mempool, block);
block += sizeof(mempool_block_header) + obj_size;
}
}
void *mempool_alloc(mempool_instance *mempool)
{
void *block;
block = DLIST_TAIL(mempool);
if(!block)
return NULL;
DLIST_DEL(mempool, block);
return ((mempool_block_header *)block)->data_addr;
}
void mempool_free(mempool_instance *mempool, void *obj)
{
void *block;
block = obj - sizeof(mempool_block_header);
DLIST_APPEND(mempool, block);
}
void mempool_destroy(mempool_instance *mempool)
{
free(mempool->pool);
mempool->pool = NULL;
}