#ifndef _MEM_POOL_H_
|
#define _MEM_POOL_H_
|
#include "mm.h"
|
#include "sem_util.h"
|
#define MEM_POOL_COND_KEY 0x8801
|
|
static int mem_pool_cond = SemUtil::get(MEM_POOL_COND_KEY, 0);
|
|
// static int mem_pool_mutex = SemUtil::get(MEM_POOL_COND_KEY, 1);
|
|
static inline void mem_pool_init(size_t heap_size) {
|
if(mm_init(heap_size)) {
|
|
}
|
}
|
|
static inline void mem_pool_destroy(void) {
|
if(mm_destroy()) {
|
SemUtil::remove(mem_pool_cond);
|
}
|
|
}
|
|
static inline void *mem_pool_malloc (size_t size) {
|
void *ptr;
|
while( (ptr = mm_malloc(size)) == NULL ) {
|
err_msg(0, "There is not enough memery to allocate, waiting someone else to free.");
|
SemUtil::set(mem_pool_cond, 0);
|
// wait for someone else to free space
|
SemUtil::dec(mem_pool_cond);
|
|
}
|
|
return ptr;
|
}
|
|
template <typename T>
|
static inline T* mem_pool_attach(int key) {
|
void *ptr;
|
// T* tptr;
|
hashtable_t *hashtable = mm_get_hashtable();
|
ptr = hashtable_get(hashtable, key);
|
// printf("mem_pool_malloc_by_key malloc before %d, %p\n", key, ptr);
|
if(ptr == NULL || ptr == (void *)1 ) {
|
ptr = mm_malloc(sizeof(T));
|
hashtable_put(hashtable, key, ptr);
|
new(ptr) T;
|
// printf("mem_pool_malloc_by_key use new %d, %p\n", key, ptr);
|
}
|
return (T*)ptr;
|
}
|
|
static inline void mem_pool_free_by_key(int key) {
|
void *ptr;
|
// T* tptr;
|
hashtable_t *hashtable = mm_get_hashtable();
|
ptr = hashtable_get(hashtable, key);
|
if(ptr != NULL) {
|
mm_free(ptr);
|
hashtable_remove(hashtable, key);
|
}
|
}
|
|
static inline void mem_pool_free (void *ptr) {
|
mm_free(ptr);
|
// notify malloc
|
SemUtil::set(mem_pool_cond, 1);
|
|
}
|
|
static inline void *mem_pool_realloc (void *ptr, size_t size) {
|
return mm_realloc(ptr, size);
|
}
|
|
static inline int mem_pool_alloc_key() {
|
hashtable_t *hashtable = mm_get_hashtable();
|
return hashtable_alloc_key(hashtable);
|
}
|
|
|
// extern int mm_checkheap(int verbose);
|
|
|
#endif
|