设为首页 加入收藏

TOP

LRU缓存算法 - C++版(二)
2014-04-06 17:34:42 来源: 作者: 【 】 浏览:180
Tags:LRU 算法  

 

  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 : "<

      

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++Tab键实现自动补全输入功能 下一篇C++通过OCCI操作Oracle数据库

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)