tlds
Transactional Operations for Linked Data Structures
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
allocator.h
Go to the documentation of this file.
1 #ifndef ALLOCATOR_H
2 #define ALLOCATOR_H
3 
4 #include <cstdint>
5 #include <malloc.h>
6 #include <atomic>
7 #include <common/assert.h>
8 
9 template<typename DataType>
10 class Allocator
11 {
12 public:
13  Allocator(uint64_t totalBytes, uint64_t threadCount, uint64_t typeSize)
14  {
15  m_totalBytes = totalBytes;
16  m_threadCount = threadCount;
17  m_typeSize = typeSize;
18  m_ticket = 0;
19  m_pool = (char*)memalign(m_typeSize, totalBytes);
20 
21  ASSERT(m_pool, "Memory pool initialization failed.");
22  }
23 
25  {
26  free(m_pool);
27  }
28 
29  //Every thread need to call init once before any allocation
30  void Init()
31  {
32  uint64_t threadId = __sync_fetch_and_add(&m_ticket, 1);
33  ASSERT(threadId < m_threadCount, "ThreadId specified should be smaller than thread count.");
34 
35  m_base = m_pool + threadId * m_totalBytes / m_threadCount;
36  m_freeIndex = 0;
37  }
38 
39  void Uninit()
40  { }
41 
42  DataType* Alloc()
43  {
44  ASSERT(m_freeIndex < m_totalBytes / m_threadCount, "out of capacity.");
45  char* ret = m_base + m_freeIndex;
46  m_freeIndex += m_typeSize;
47 
48  return (DataType*)ret;
49  }
50 
51 private:
52  char* m_pool;
53  uint64_t m_totalBytes; //number of elements T in the pool
54  uint64_t m_threadCount;
55  uint64_t m_ticket;
56  uint64_t m_typeSize;
57 
58  static __thread char* m_base;
59  static __thread uint64_t m_freeIndex;
60 };
61 
62 template<typename T>
63 __thread char* Allocator<T>::m_base;
64 
65 template<typename T>
66 __thread uint64_t Allocator<T>::m_freeIndex;
67 
68 #endif /* end of include guard: ALLOCATOR_H */
uint64_t m_totalBytes
Definition: allocator.h:53
void Init()
Definition: allocator.h:30
Definition: allocator.h:10
#define ASSERT(condition,...)
Definition: assert.h:27
bool ret
Definition: stmskip.cc:242
void Uninit()
Definition: allocator.h:39
#define __sync_fetch_and_add(p, a)
Definition: icc-sync.hpp:57
static __thread char * m_base
Definition: allocator.h:58
~Allocator()
Definition: allocator.h:24
static __thread uint64_t m_freeIndex
Definition: allocator.h:59
DataType * Alloc()
Definition: allocator.h:42
uint64_t m_threadCount
Definition: allocator.h:54
uint64_t m_typeSize
Definition: allocator.h:56
uint64_t m_ticket
Definition: allocator.h:55
Allocator(uint64_t totalBytes, uint64_t threadCount, uint64_t typeSize)
Definition: allocator.h:13
char * m_pool
Definition: allocator.h:52