netgen/libsrc/general/optmem.cpp

75 lines
1.8 KiB
C++
Raw Normal View History

2009-01-13 04:40:13 +05:00
/**************************************************************************/
2012-06-16 22:58:46 +06:00
/* File: optmem.cpp */
2009-01-13 04:40:13 +05:00
/* Author: Joachim Schoeberl */
/* Date: 04. Apr. 97 */
/**************************************************************************/
/*
2009-01-25 17:35:25 +05:00
Abstract data type Array
2009-01-13 04:40:13 +05:00
*/
#include <mystdlib.h>
#include <myadt.hpp>
namespace netgen
{
2016-02-22 22:43:51 +05:00
static mutex block_allocator_mutex;
2009-01-13 04:40:13 +05:00
BlockAllocator :: BlockAllocator (unsigned asize, unsigned ablocks)
: bablocks (0)
{
if (asize < sizeof(void*))
asize = sizeof(void*);
size = asize;
blocks = ablocks;
freelist = NULL;
}
BlockAllocator :: ~BlockAllocator ()
{
2014-10-19 19:53:57 +06:00
// cout << "****************** delete BlockAllocator " << endl;
2009-01-13 04:40:13 +05:00
for (int i = 0; i < bablocks.Size(); i++)
delete [] bablocks[i];
2014-10-19 19:53:57 +06:00
bablocks.SetSize(0);
2009-01-13 04:40:13 +05:00
}
void * BlockAllocator :: Alloc ()
{
2015-01-20 22:41:16 +05:00
void * p;
{
2016-02-22 22:43:51 +05:00
lock_guard<mutex> guard(block_allocator_mutex);
2015-01-20 22:41:16 +05:00
// return new char[size];
if (!freelist)
{
// cout << "freelist = " << freelist << endl;
// cout << "BlockAlloc: " << size*blocks << endl;
char * hcp = new char [size * blocks];
bablocks.Append (hcp);
bablocks.Last() = hcp;
for (unsigned i = 0; i < blocks-1; i++)
*(void**)&(hcp[i * size]) = &(hcp[ (i+1) * size]);
*(void**)&(hcp[(blocks-1)*size]) = NULL;
freelist = hcp;
}
p = freelist;
freelist = *(void**)freelist;
}
2009-01-13 04:40:13 +05:00
return p;
}
void BlockAllocator :: Free (void * p)
{
2015-01-20 22:41:16 +05:00
{
2016-02-22 22:43:51 +05:00
lock_guard<mutex> guard(block_allocator_mutex);
2015-01-20 22:41:16 +05:00
if (bablocks.Size())
{
*(void**)p = freelist;
freelist = p;
}
}
2009-01-13 04:40:13 +05:00
}
2015-01-20 22:41:16 +05:00
2009-01-13 04:40:13 +05:00
}