freelist_ = reblock;
}
return p;
}
}
void deallocte(void* pUserData)
{
if(!belong_to(pUserData))
{
free(pUserData);
return;
}
#ifdef EANBLE_MULTI_THREAD
std::unique_lock<std::mutex> guard(this->mtx_);
#endif
memblock_head_t* curh = HEAD_LOC(pUserData);
memblock_foot_t* lf = LEFT_FOOT_LOC(curh);
memblock_head_t* rh = RIGHT_HEAD_LOC(curh);
bool vlf = is_valid_leftf(lf);
bool vrh = is_valid_righth(rh);
#ifdef _DEBUG
memset(pUserData, 0x0, curh->size - reserved_size);
#endif
if( ( vlf && lf->uplink->unused ) && (!vrh || !rh->unused) )
{ // merge curret to left block
lf->uplink->next = curh->next;
if(curh->next != nullptr)
curh->next->prev = lf->uplink;
lf->uplink->size += curh->size;
UPDATE_FOOT(lf->uplink);
this->freelist_ = lf->uplink;
}
else if( (vrh && rh->unused) && (!vlf || !lf->uplink->unused ) )
{ // merge right to current block
curh->unused = true;
curh->next = rh->next;
if(rh->next != nullptr)
rh->next->prev = curh;
curh->size += rh->size;
UPDATE_FOOT(curh);
this->freelist_ = curh;
}
else if( (vlf && lf->uplink->unused) && (vrh && rh->unused) )
{ // merge current and right to left block
lf->uplink->next = rh->next;
if(rh->next != nullptr)
rh->next->prev = lf->uplink;
lf->uplink->size += (curh->size + rh->size);
UPDATE_FOOT(lf->uplink);
this->freelist_ = lf->uplink;
}
else {
// no need merge
curh->unused = true;
this->freelist_ = curh;
}
}
bool belong_to(void* p)
{
return p >= this->memory_ && p < ( (char*)this->memory_ + this->memory_size_ );
}
bool is_valid_leftf(void* lf)
{
return ((char*)lf > ( (char*)this->memory_ + sizeof(memblock_head_t)) );
}
bool is_valid_righth(void* rh)
{
return (char*)rh < ((char*)this->memory_ + memory_size_ - sizeof(memblock_foot_t) );
}
private:
void* memory_;
size_t memory_size_; // memory total size;
memblock_head_t* freelist_;
#ifdef EANBLE_MULTI_THREAD
std::mutex mtx_;
#endif
};
int main(int argc, char** argv)
{
/*apr_allocator_t* allocator;
apr_allocator_create(&allocator);
apr_memnode_t* node = apr_allocator_alloc(allocator, SZ(3, k));
apr_allocator_free(allocator, node);
node = apr_allocator_alloc(allocator, SZ(3, k));*/
int times = 1000000;
mempool pool;
char* p1 = (char*)pool.allocate(25);
strcpy(p1, "hello world");
char* p2 = (char*)pool.allocate(25);
char* p3 = (char*)pool.allocate(25);
char* p4 = (char*)pool.allocate(25);
pool.deallocte(p2);
pool.deallocte(p4);
pool.deallocte(p3);
pool.deallocte(p1);
double end ;
clock_t start = clock();
for(int i = 0; i < times; ++i)
{
void* p = malloc(rrand(sizeof(int), 8192 * 2));
if(p)
free(p);
}
end[0] = (clock() - start) / (double)CLOCKS_PER_SEC;
start = clock();
for(int i = 0; i < times; ++i)
{
void* p = pool.allocate(rrand(sizeof(int), 8192 * 2));
if(p)
pool.deallocte(p);
}
end = (clock() - start) / (double)CLOCKS_PER_SEC;
start = clock();
for(int i = 0; i < times; ++i)
{