LRU缓存算法 - C++版(二)

2014-04-06 17:34:42 · 作者: · 浏览: 184

 

  hash_map* > cached_map;

  vector* > cached_entries;

  Node * head, *tail;

  Node * entries;

  bool pthread_safe;

  pthread_mutex_t cached_mutex;

  };

  template

  void LRUCache::Put(K key , D data){

  cached_lock();

  Node *node = cached_map[key];

  if(node){

  detach(node);

  node->data = data;

  attach(node);

  }

  else{

  if(cached_entries.empty()){

  node = tail->prev;

  detach(node);

  cached_map.erase(node->key);

  }

  else{

  node = cached_entries.back();

  cached_entries.pop_back();

  }

  node->key = key;

  node->data = data;

  cached_map[key] = node;

  attach(node);

  }

  cached_unlock();

  }

  template

  D LRUCache::Get(K key){

  cached_lock();

  Node *node = cached_map[key];

  if(node){

  detach(node);

  attach(node);

  cached_unlock();

  return node->data;

  }

  else{

  cached_unlock();

  return D();

  }

  }

  #endif

  测试用例:

  [cpp] view plaincopy

  /*

  Compile:

  g++ -o app app.cpp LRUCache.cpp -lpthread

  Run:

  ./app

  */

  #include

  #include

  #include "LRUCache.h"

  using namespace std;

  int

  main(void){

  //int k = 10 ,

  // max = 100;

  int k = 100000 ,

  max = 1000000;

  LRUCache * lru_cache = new LRUCache(k , true);

  int tmp = 0;

  for(int i = 0 ; i < 2*k ; ++i){

  tmp = rand() % max;

  lru_cache->Put(tmp, tmp + 1000000);

  cout<

  }

  for(int i = 0 ; i < k ; ++i){

  tmp = rand() % max;

  if(lru_cache->Get(tmp) == 0)

  cout《"miss : "<

  else

  cout《"hit : "<