mem_pool.h 9.4 KB
Newer Older
L
Longda 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Longda on 2010
//

15
#pragma once
L
Longda 已提交
16 17 18 19 20 21

#include <queue>
#include <list>
#include <set>
#include <string>
#include <sstream>
22 23
#include <functional>
#include <memory>
L
Longda 已提交
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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

#include "common/lang/mutex.h"
#include "common/log/log.h"
#include "common/os/os.h"

namespace common {

#define DEFAULT_ITEM_NUM_PER_POOL 128
#define DEFAULT_POOL_NUM 1

typedef bool (*match)(void *item, void *input_arg);

template <class T>
class MemPool {
public:
  MemPool(const char *tag) : name(tag)
  {
    this->size = 0;

    pthread_mutexattr_t mutexatr;
    pthread_mutexattr_init(&mutexatr);
    pthread_mutexattr_settype(&mutexatr, PTHREAD_MUTEX_RECURSIVE);

    MUTEX_INIT(&mutex, &mutexatr);
  }

  virtual ~MemPool()
  {
    MUTEX_DESTROY(&mutex);
  }

  /**
   * init memory pool, the major job is to alloc memory for memory pool
   * @param pool_num, memory pool's number
   * @param item_num_per_pool, how many items per pool.
   * @return
   */
  virtual int init(
      bool dynamic = true, int pool_num = DEFAULT_POOL_NUM, int item_num_per_pool = DEFAULT_ITEM_NUM_PER_POOL) = 0;

  /**
   * Do cleanup job for memory pool
   */
  virtual void cleanup() = 0;

  /**
   * If dynamic has been set, extend current memory pool,
   */
  virtual int extend() = 0;

  /**
   * Alloc one frame from memory Pool
   * @return
   */
  virtual T *alloc() = 0;

  /**
   * Free one item, the resouce will return to memory Pool
   * @param item
   */
  virtual void free(T *item) = 0;

  /**
   * Print the MemPool status
   * @return
   */
  virtual std::string to_string() = 0;

  const std::string get_name() const
  {
    return name;
  }
  bool is_dynamic() const
  {
    return dynamic;
  }
  int get_size() const
  {
    return size;
  }

protected:
  pthread_mutex_t mutex;
  int size;
  bool dynamic;
  std::string name;
};

/**
 * MemoryPoolSimple is a simple Memory Pool manager,
 */
template <class T>
class MemPoolSimple : public MemPool<T> {
public:
  MemPoolSimple(const char *tag) : MemPool<T>(tag)
  {}

  virtual ~MemPoolSimple()
  {
    cleanup();
  }

  /**
   * init memory pool, the major job is to alloc memory for memory pool
   * @param pool_num, memory pool's number
   * @param item_num_per_pool, how many items per pool.
羽飞's avatar
羽飞 已提交
130
   * @return 0 for success and others failure
L
Longda 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
   */
  int init(bool dynamic = true, int pool_num = DEFAULT_POOL_NUM, int item_num_per_pool = DEFAULT_ITEM_NUM_PER_POOL);

  /**
   * Do cleanup job for memory pool
   */
  void cleanup();

  /**
   * If dynamic has been set, extend current memory pool,
   */
  int extend();

  /**
   * Alloc one frame from memory Pool
   * @return
   */
  T *alloc();

  /**
   * Free one item, the resouce will return to memory Pool
   * @param item
   */
  void free(T *item);

  /**
   * Print the MemPool status
   * @return
   */
  std::string to_string();

  int get_item_num_per_pool() const
  {
    return item_num_per_pool;
  }

  int get_used_num()
  {
    MUTEX_LOCK(&this->mutex);
    auto num = used.size();
    MUTEX_UNLOCK(&this->mutex);
    return num;
  }

protected:
  std::list<T *> pools;
  std::set<T *> used;
  std::list<T *> frees;
  int item_num_per_pool;
};

template <class T>
int MemPoolSimple<T>::init(bool dynamic, int pool_num, int item_num_per_pool)
{
  if (pools.empty() == false) {
    LOG_WARN("Memory pool has been initialized, but still begin to be initialized, this->name:%s.", this->name.c_str());
    return 0;
  }

  if (pool_num <= 0 || item_num_per_pool <= 0) {
    LOG_ERROR("Invalid arguments,  pool_num:%d, item_num_per_pool:%d, this->name:%s.",
        pool_num,
        item_num_per_pool,
        this->name.c_str());
    return -1;
  }

  this->item_num_per_pool = item_num_per_pool;
  // in order to init memory pool, enable dynamic here
  this->dynamic = true;
  for (int i = 0; i < pool_num; i++) {
    if (extend() < 0) {
      cleanup();
      return -1;
    }
  }
  this->dynamic = dynamic;

  LOG_INFO("Extend one pool, this->size:%d, item_num_per_pool:%d, this->name:%s.",
      this->size,
      item_num_per_pool,
      this->name.c_str());
  return 0;
}

template <class T>
void MemPoolSimple<T>::cleanup()
{
  if (pools.empty() == true) {
    LOG_WARN("Begin to do cleanup, but there is no memory pool, this->name:%s!", this->name.c_str());
    return;
  }

  MUTEX_LOCK(&this->mutex);

  used.clear();
  frees.clear();
  this->size = 0;

  for (typename std::list<T *>::iterator iter = pools.begin(); iter != pools.end(); iter++) {
    T *pool = *iter;

    delete[] pool;
  }
  pools.clear();
  MUTEX_UNLOCK(&this->mutex);
  LOG_INFO("Successfully do cleanup, this->name:%s.", this->name.c_str());
}

template <class T>
int MemPoolSimple<T>::extend()
{
  if (this->dynamic == false) {
    LOG_ERROR("Disable dynamic extend memory pool, but begin to extend, this->name:%s", this->name.c_str());
    return -1;
  }

  MUTEX_LOCK(&this->mutex);
  T *pool = new T[item_num_per_pool];
  if (pool == nullptr) {
    MUTEX_UNLOCK(&this->mutex);
    LOG_ERROR("Failed to extend memory pool, this->size:%d, item_num_per_pool:%d, this->name:%s.",
        this->size,
        item_num_per_pool,
        this->name.c_str());
    return -1;
  }

  pools.push_back(pool);
  this->size += item_num_per_pool;
  for (int i = 0; i < item_num_per_pool; i++) {
    frees.push_back(pool + i);
  }
  MUTEX_UNLOCK(&this->mutex);

  LOG_INFO("Extend one pool, this->size:%d, item_num_per_pool:%d, this->name:%s.",
      this->size,
      item_num_per_pool,
      this->name.c_str());
  return 0;
}

template <class T>
T *MemPoolSimple<T>::alloc()
{
  MUTEX_LOCK(&this->mutex);
  if (frees.empty() == true) {
    if (this->dynamic == false) {
      MUTEX_UNLOCK(&this->mutex);
      return nullptr;
    }

    if (extend() < 0) {
      MUTEX_UNLOCK(&this->mutex);
      return nullptr;
    }
  }
  T *buffer = frees.front();
  frees.pop_front();

  used.insert(buffer);

  MUTEX_UNLOCK(&this->mutex);
294
  new (buffer) T();
L
Longda 已提交
295 296 297 298 299 300
  return buffer;
}

template <class T>
void MemPoolSimple<T>::free(T *buf)
{
301 302
  buf->~T();
  
L
Longda 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  MUTEX_LOCK(&this->mutex);

  size_t num = used.erase(buf);
  if (num == 0) {
    MUTEX_UNLOCK(&this->mutex);
    LOG_WARN("No entry of %p in %s.", buf, this->name.c_str());
    print_stacktrace();
    return;
  }

  frees.push_back(buf);

  MUTEX_UNLOCK(&this->mutex);
  return;  // TODO for test
}

template <class T>
std::string MemPoolSimple<T>::to_string()
{
  std::stringstream ss;

  ss << "name:" << this->name << ","
     << "dyanmic:" << this->dynamic << ","
     << "size:" << this->size << ","
     << "pool_size:" << this->pools.size() << ","
     << "used_size:" << this->used.size() << ","
     << "free_size:" << this->frees.size();
  return ss.str();
}

class MemPoolItem {
334 335 336
public:
  using unique_ptr = std::unique_ptr<void, std::function<void(void * const)>>;

L
Longda 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
public:
  MemPoolItem(const char *tag) : name(tag)
  {
    this->size = 0;

    pthread_mutexattr_t mutexatr;
    pthread_mutexattr_init(&mutexatr);
    pthread_mutexattr_settype(&mutexatr, PTHREAD_MUTEX_RECURSIVE);

    MUTEX_INIT(&mutex, &mutexatr);
  }

  virtual ~MemPoolItem()
  {
    cleanup();
    MUTEX_DESTROY(&mutex);
  }

  /**
   * init memory pool, the major job is to alloc memory for memory pool
   * @param pool_num, memory pool's number
   * @param item_num_per_pool, how many items per pool.
   * @return
   */
  int init(int item_size, bool dynamic = true, int pool_num = DEFAULT_POOL_NUM,
      int item_num_per_pool = DEFAULT_ITEM_NUM_PER_POOL);

  /**
   * Do cleanup job for memory pool
   */
  void cleanup();

  /**
   * If dynamic has been set, extend current memory pool,
   */
  int extend();

  /**
   * Alloc one frame from memory Pool
   * @return
   */
  void *alloc();
379
  unique_ptr alloc_unique_ptr();
L
Longda 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

  /**
   * Free one item, the resouce will return to memory Pool
   * @param item
   */
  void free(void *item);

  /**
   * Check whether this item has been used before.
   * @param item
   * @return
   */
  bool is_used(void *item)
  {
    MUTEX_LOCK(&mutex);
    auto it = used.find(item);
    MUTEX_UNLOCK(&mutex);
    return it != used.end();
  }

  std::string to_string()
  {

    std::stringstream ss;

    ss << "name:" << this->name << ","
       << "dyanmic:" << this->dynamic << ","
       << "size:" << this->size << ","
       << "pool_size:" << this->pools.size() << ","
       << "used_size:" << this->used.size() << ","
       << "free_size:" << this->frees.size();
    return ss.str();
  }

  const std::string get_name() const
  {
    return name;
  }
  bool is_dynamic() const
  {
    return dynamic;
  }
  int get_size() const
  {
    return size;
  }
  int get_item_size() const
  {
    return item_size;
  }
  int get_item_num_per_pool() const
  {
    return item_num_per_pool;
  }

  int get_used_num()
  {
    MUTEX_LOCK(&mutex);
    auto num = used.size();
    MUTEX_UNLOCK(&mutex);
    return num;
  }

protected:
  pthread_mutex_t mutex;
  std::string name;
  bool dynamic;
  int size;
  int item_size;
  int item_num_per_pool;

  std::list<void *> pools;
  std::set<void *> used;
  std::list<void *> frees;
};

}  // namespace common