CernVM-FS  2.12.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
item_mem.cc
Go to the documentation of this file.
1 
5 #include "item_mem.h"
6 
7 #include <cassert>
8 #include <cstdlib>
9 
10 #include "util/concurrency.h"
11 #include "util/exception.h"
12 
14 
15 
16 void ItemAllocator::Free(void *ptr) {
17  MutexLockGuard guard(lock_);
18 
20  M->Free(ptr);
21  unsigned N = malloc_arenas_.size();
22  if ((N > 1) && M->IsEmpty()) {
23  for (unsigned i = 0; i < N; ++i) {
24  if (malloc_arenas_[i] == M) {
25  delete malloc_arenas_[i];
26  atomic_xadd64(&total_allocated_, -static_cast<int>(kArenaSize));
27  malloc_arenas_.erase(malloc_arenas_.begin() + i);
28  idx_last_arena_ = 0;
29  return;
30  }
31  }
32  PANIC(NULL);
33  }
34 }
35 
36 
37 ItemAllocator::ItemAllocator() : idx_last_arena_(0) {
38  int retval = pthread_mutex_init(&lock_, NULL);
39  assert(retval == 0);
40 
41  malloc_arenas_.push_back(new MallocArena(kArenaSize));
42  atomic_xadd64(&total_allocated_, kArenaSize);
43 }
44 
45 
47  for (unsigned i = 0; i < malloc_arenas_.size(); ++i) {
48  atomic_xadd64(&total_allocated_, -static_cast<int>(kArenaSize));
49  delete malloc_arenas_[i];
50  }
51  pthread_mutex_destroy(&lock_);
52 }
53 
54 
55 void *ItemAllocator::Malloc(unsigned size) {
56  MutexLockGuard guard(lock_);
57 
58  void *p = malloc_arenas_[idx_last_arena_]->Malloc(size);
59  if (p != NULL)
60  return p;
61  unsigned N = malloc_arenas_.size();
62  for (unsigned i = 0; i < N; ++i) {
63  p = malloc_arenas_[i]->Malloc(size);
64  if (p != NULL) {
65  idx_last_arena_ = i;
66  return p;
67  }
68  }
69  idx_last_arena_ = N;
71  atomic_xadd64(&total_allocated_, kArenaSize);
72  malloc_arenas_.push_back(M);
73  p = M->Malloc(size);
74  assert(p != NULL);
75  return p;
76 }
int64_t atomic_int64
Definition: atomic.h:18
static MallocArena * GetMallocArena(void *ptr, unsigned arena_size)
Definition: malloc_arena.h:77
#define PANIC(...)
Definition: exception.h:29
void * Malloc(unsigned size)
Definition: item_mem.cc:55
assert((mem||(size==0))&&"Out Of Memory")
std::vector< MallocArena * > malloc_arenas_
Definition: item_mem.h:34
unsigned idx_last_arena_
Definition: item_mem.h:38
void Free(void *ptr)
Definition: malloc_arena.cc:55
bool IsEmpty() const
Definition: malloc_arena.h:95
void * Malloc(const uint32_t size)
Definition: mutex.h:42
static atomic_int64 total_allocated_
Definition: item_mem.h:32
static const unsigned kArenaSize
Definition: item_mem.h:31
static void size_t size
Definition: smalloc.h:54
pthread_mutex_t lock_
Definition: item_mem.h:39
void Free(void *ptr)
Definition: item_mem.cc:16