File: optmem.cpp

package info (click to toggle)
netgen 6.2.2601%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,076 kB
  • sloc: cpp: 166,627; tcl: 6,310; python: 2,868; sh: 528; makefile: 90
file content (75 lines) | stat: -rw-r--r-- 1,943 bytes parent folder | download | duplicates (2)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**************************************************************************/
/* File:   optmem.cpp                                                     */
/* Author: Joachim Schoeberl                                              */
/* Date:   04. Apr. 97                                                    */
/**************************************************************************/

/* 
   Abstract data type NgArray
*/


#include <mystdlib.h>
#include <myadt.hpp>

namespace netgen
{
  // static mutex block_allocator_mutex;

  BlockAllocator :: BlockAllocator (unsigned asize, unsigned ablocks)
    : bablocks (0)
  {
    if (asize < sizeof(void*))
      asize = sizeof(void*);
    size = asize;
    blocks = ablocks;
    freelist = NULL;
  }

  BlockAllocator :: ~BlockAllocator ()
  {
    lock_guard<mutex> guard(block_allocator_mutex);     
    // cout << "****************** delete BlockAllocator " << endl;
    for (int i = 0; i < bablocks.Size(); i++)
      delete [] bablocks[i];
    bablocks.SetSize(0);
  }

  void * BlockAllocator :: Alloc ()
  {
    void * p;
    {
      lock_guard<mutex> guard(block_allocator_mutex); 
      //  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;
    }
    return p;
  }

  void BlockAllocator :: Free (void * p)
  {
    {
      lock_guard<mutex> guard(block_allocator_mutex); 
      if (bablocks.Size())
        {
          *(void**)p = freelist;
          freelist = p;
        }
    }
  }

}