鸿 网 互 联 www.68idc.cn

当前位置 : 服务器租用 > 编程语言开发 > c++ > >

循环列表内存池

来源:互联网 作者:佚名 时间:2016-06-16 09:03
一读线程和一写线程可无锁,多线程读写锁分离 无 #include pthread.htypedef unsigned int uint32_t;typedef struct { char* data; uint32_t size; uint32_t used;} memory_slot_t;class circulating_memory_pool_c {public: circulating_memory_pool_c(uint3
一读线程和一写线程可无锁,多线程读写锁分离 <无>
#include <pthread.h>

typedef unsigned int uint32_t;

typedef struct {
  char*    data;
  uint32_t size;
  uint32_t used;
} memory_slot_t;


class circulating_memory_pool_c {
public:
  circulating_memory_pool_c(uint32_t pool_size = 10, uint32_t slot_size = 1000);
  ~circulating_memory_pool_c();
  bool get_idle_slot(memory_slot_t** slot);
  bool get_used_slot(memory_slot_t** slot);

private:
  memory_slot_t* m_list;
  uint32_t m_head;
  uint32_t m_tail;
  uint32_t m_size;
  uint32_t m_used;

private:
  pthread_mutex_t m_used_mutex;
  pthread_mutex_t m_idle_mutex;
};

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "circulating_memory_pool.h"


circulating_memory_pool_c::circulating_memory_pool_c(uint32_t pool_size, uint32_t slot_size) {
  m_list = new memory_slot_t[pool_size];
  m_size = 0;
  for (uint32_t i = 0; i < pool_size; i++) {
    m_list[i].size = slot_size;
    m_list[i].used = 0;
    m_list[i].data = new char[slot_size + 1];
    memset(m_list[i].data, 0, slot_size + 1);
    m_size++;
  }
  m_head = 0;
  m_tail = 1;
  m_used = 0;
  pthread_mutex_init(&m_used_mutex, NULL);
  pthread_mutex_init(&m_idle_mutex, NULL);
}

circulating_memory_pool_c::~circulating_memory_pool_c() {
  if (m_list != NULL) {
    for (uint32_t i = 0; i < m_size; i++) {
      if (m_list[i].data != NULL) {
        delete[] m_list[i].data;
        m_list[i].data = NULL;
      }
    }
    delete[] m_list;
    m_list = NULL;
  }
  pthread_mutex_destroy(&m_used_mutex);
  pthread_mutex_destroy(&m_idle_mutex);
}

bool circulating_memory_pool_c::get_idle_slot(memory_slot_t** slot) {
  pthread_mutex_lock(&m_idle_mutex);
  if (m_tail == m_head) {
    // printf("pool full.\n");
    pthread_mutex_unlock(&m_idle_mutex);
    return false;
  }
  (*slot) = m_list + m_tail;
  m_tail = (m_tail + 1) % m_size;
  m_used++;
  pthread_mutex_unlock(&m_idle_mutex);
  return true;
}

bool circulating_memory_pool_c::get_used_slot(memory_slot_t** slot) {
  pthread_mutex_lock(&m_used_mutex);
  if (m_head == m_tail) {
    // printf("pool empty.\n");
    pthread_mutex_unlock(&m_used_mutex);
    return false;
  }
  (*slot) = m_list + m_head;
  m_head = (m_head + 1) % m_size;
  m_used--;
  pthread_mutex_unlock(&m_used_mutex);
  return true;
}
网友评论
<