FEI  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
fei_Pool.hpp
1 /*--------------------------------------------------------------------*/
2 /* Copyright 2005 Sandia Corporation. */
3 /* Under the terms of Contract DE-AC04-94AL85000, there is a */
4 /* non-exclusive license for use of this work by or on behalf */
5 /* of the U.S. Government. Export of this program may require */
6 /* a license from the United States Government. */
7 /*--------------------------------------------------------------------*/
8 
9 #ifndef _fei_Pool_hpp_
10 #define _fei_Pool_hpp_
11 
12 #include "fei_macros.hpp"
13 
14 #include <cstdlib>
15 
16 #ifndef FEI_ALLOC_CHUNK_SIZE_K
17 #define FEI_ALLOC_CHUNK_SIZE_K 512
18 #endif
19 
20 //The macro FEI_ALLOC_CHUNK_SIZE_K determines the number
21 //of kilobytes that each internally-allocated chunk of memory will
22 //occupy. The fei_Pool object will then dispense "sub-chunks"
23 //of memory having size determined by the argument to the class
24 //constructor.
25 
26 class fei_Pool {
27  public:
28  fei_Pool(unsigned int n); // n is the size of elements
29  ~fei_Pool();
30 
31  void* alloc(); //allocate one element
32  void free(void* b); //put an element back into the pool
33  struct Link { Link* next; };
34 
35  private:
36  struct Chunk {
37  //Stroustrup's comment:
38  //slightly less than specified K so that a chunk will fit in
39  //allocation area first to get stringent alignment
40  enum { size = FEI_ALLOC_CHUNK_SIZE_K*1024-16 };
41  char mem[size];
42  Chunk* next;
43  };
44 
45  Chunk* chunks;
46  const unsigned int esize;
47  Link* head;
48 
49  fei_Pool(const fei_Pool&);//private copy constructor
50  fei_Pool& operator=(const fei_Pool&);//private assignment operator
51  void grow(); //make pool larger
52 };
53 
54 inline void* fei_Pool::alloc()
55 {
56  if (head == NULL) {
57  grow();
58  }
59  Link* p = head; //return first element
60  head = p->next;
61  return p;
62 }
63 
64 inline void fei_Pool::free(void* b)
65 {
66  Link* p = static_cast<Link*>(b);
67  p->next = head; //put b back as first element
68  head = p;
69 }
70 
71 #endif
72