├── images └── hitTest.jpg ├── KICachePolicy.h ├── CMakeLists.txt ├── KArcCache ├── KArcCacheNode.h ├── KArcCache.h ├── KArcLruPart.h └── KArcLfuPart.h ├── .vscode └── settings.json ├── README.md ├── KLruCache.h ├── KLfuCache.h ├── testAllCachePolicy.cpp └── LICENSE /images/hitTest.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youngyangyang04/KamaCache/HEAD/images/hitTest.jpg -------------------------------------------------------------------------------- /KICachePolicy.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace KamaCache 4 | { 5 | 6 | template 7 | class KICachePolicy 8 | { 9 | public: 10 | virtual ~KICachePolicy() {}; 11 | 12 | // 添加缓存接口 13 | virtual void put(Key key, Value value) = 0; 14 | 15 | // key是传入参数 访问到的值以传出参数的形式返回 | 访问成功返回true 16 | virtual bool get(Key key, Value& value) = 0; 17 | // 如果缓存中能找到key,则直接返回value 18 | virtual Value get(Key key) = 0; 19 | 20 | }; 21 | 22 | } // namespace KamaCache -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # 设置最低 CMake 版本要求 2 | cmake_minimum_required(VERSION 3.10) 3 | 4 | # 设置项目名称 5 | project(KCacheSystem) 6 | 7 | # 设置 C++ 标准 8 | set(CMAKE_CXX_STANDARD 17) 9 | set(CMAKE_CXX_STANDARD_REQUIRED True) 10 | 11 | # 指定源文件目录下的所有 .cpp 文件 12 | file(GLOB SOURCES "*.cpp") 13 | 14 | # 设置目标可执行文件 15 | add_executable(main ${SOURCES}) 16 | 17 | # 清理中间的 .o 文件 18 | set_target_properties(main PROPERTIES CLEAN_DIRECT_OUTPUT 1) 19 | 20 | # 额外的编译选项(可根据需要启用) 21 | # target_compile_options(main PRIVATE -Wall -Wextra -O2) -------------------------------------------------------------------------------- /KArcCache/KArcCacheNode.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace KamaCache 6 | { 7 | 8 | template 9 | class ArcNode 10 | { 11 | private: 12 | Key key_; 13 | Value value_; 14 | size_t accessCount_; 15 | std::weak_ptr prev_; 16 | std::shared_ptr next_; 17 | 18 | public: 19 | ArcNode() : accessCount_(1), next_(nullptr) {} 20 | 21 | ArcNode(Key key, Value value) 22 | : key_(key) 23 | , value_(value) 24 | , accessCount_(1) 25 | , next_(nullptr) 26 | {} 27 | 28 | // Getters 29 | Key getKey() const { return key_; } 30 | Value getValue() const { return value_; } 31 | size_t getAccessCount() const { return accessCount_; } 32 | 33 | // Setters 34 | void setValue(const Value& value) { value_ = value; } 35 | void incrementAccessCount() { ++accessCount_; } 36 | 37 | template friend class ArcLruPart; 38 | template friend class ArcLfuPart; 39 | }; 40 | 41 | } // namespace KamaCache -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "thread": "cpp", 4 | "cctype": "cpp", 5 | "clocale": "cpp", 6 | "cmath": "cpp", 7 | "cstdarg": "cpp", 8 | "cstddef": "cpp", 9 | "cstdio": "cpp", 10 | "cstdlib": "cpp", 11 | "cstring": "cpp", 12 | "ctime": "cpp", 13 | "cwchar": "cpp", 14 | "cwctype": "cpp", 15 | "array": "cpp", 16 | "atomic": "cpp", 17 | "*.tcc": "cpp", 18 | "chrono": "cpp", 19 | "condition_variable": "cpp", 20 | "cstdint": "cpp", 21 | "deque": "cpp", 22 | "list": "cpp", 23 | "unordered_map": "cpp", 24 | "vector": "cpp", 25 | "exception": "cpp", 26 | "algorithm": "cpp", 27 | "functional": "cpp", 28 | "iterator": "cpp", 29 | "map": "cpp", 30 | "memory": "cpp", 31 | "memory_resource": "cpp", 32 | "numeric": "cpp", 33 | "optional": "cpp", 34 | "random": "cpp", 35 | "ratio": "cpp", 36 | "string": "cpp", 37 | "string_view": "cpp", 38 | "system_error": "cpp", 39 | "tuple": "cpp", 40 | "type_traits": "cpp", 41 | "utility": "cpp", 42 | "fstream": "cpp", 43 | "initializer_list": "cpp", 44 | "iomanip": "cpp", 45 | "iosfwd": "cpp", 46 | "iostream": "cpp", 47 | "istream": "cpp", 48 | "limits": "cpp", 49 | "mutex": "cpp", 50 | "new": "cpp", 51 | "ostream": "cpp", 52 | "sstream": "cpp", 53 | "stdexcept": "cpp", 54 | "streambuf": "cpp", 55 | "cinttypes": "cpp", 56 | "typeinfo": "cpp" 57 | } 58 | } -------------------------------------------------------------------------------- /KArcCache/KArcCache.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../KICachePolicy.h" 4 | #include "KArcLruPart.h" 5 | #include "KArcLfuPart.h" 6 | #include 7 | 8 | namespace KamaCache 9 | { 10 | 11 | template 12 | class KArcCache : public KICachePolicy 13 | { 14 | public: 15 | explicit KArcCache(size_t capacity = 10, size_t transformThreshold = 2) 16 | : capacity_(capacity) 17 | , transformThreshold_(transformThreshold) 18 | , lruPart_(std::make_unique>(capacity, transformThreshold)) 19 | , lfuPart_(std::make_unique>(capacity, transformThreshold)) 20 | {} 21 | 22 | ~KArcCache() override = default; 23 | 24 | void put(Key key, Value value) override 25 | { 26 | checkGhostCaches(key); 27 | 28 | // 检查 LFU 部分是否存在该键 29 | bool inLfu = lfuPart_->contain(key); 30 | // 更新 LRU 部分缓存 31 | lruPart_->put(key, value); 32 | // 如果 LFU 部分存在该键,则更新 LFU 部分 33 | if (inLfu) 34 | { 35 | lfuPart_->put(key, value); 36 | } 37 | } 38 | 39 | bool get(Key key, Value& value) override 40 | { 41 | checkGhostCaches(key); 42 | 43 | bool shouldTransform = false; 44 | if (lruPart_->get(key, value, shouldTransform)) 45 | { 46 | if (shouldTransform) 47 | { 48 | lfuPart_->put(key, value); 49 | } 50 | return true; 51 | } 52 | return lfuPart_->get(key, value); 53 | } 54 | 55 | Value get(Key key) override 56 | { 57 | Value value{}; 58 | get(key, value); 59 | return value; 60 | } 61 | 62 | private: 63 | bool checkGhostCaches(Key key) 64 | { 65 | bool inGhost = false; 66 | if (lruPart_->checkGhost(key)) 67 | { 68 | if (lfuPart_->decreaseCapacity()) 69 | { 70 | lruPart_->increaseCapacity(); 71 | } 72 | inGhost = true; 73 | } 74 | else if (lfuPart_->checkGhost(key)) 75 | { 76 | if (lruPart_->decreaseCapacity()) 77 | { 78 | lfuPart_->increaseCapacity(); 79 | } 80 | inGhost = true; 81 | } 82 | return inGhost; 83 | } 84 | 85 | private: 86 | size_t capacity_; 87 | size_t transformThreshold_; 88 | std::unique_ptr> lruPart_; 89 | std::unique_ptr> lfuPart_; 90 | }; 91 | 92 | } // namespace KamaCache -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # KamaCache 2 | 3 | > **本项目目前只在[知识星球](https://programmercarl.com/other/kstar.html)答疑并维护**。 4 | 5 | 最近很多录友在问:有没有比较小,但又比较完整的项目。 6 | 7 | 最近[知识星球](https://programmercarl.com/other/kstar.html)里里刚刚发布了 C++版本缓存系统,这个小项目。 8 | 9 | 代码量不大,只有1100行。 10 | 11 | 一般的话,每天花 6-8个小时,7天就可以学完。 12 | 13 | 做这个项目的基础要求: 14 | 15 | 熟悉C++语法,学会C++11常用特性即可,了解操作系统相关知识,有网络编程经验更佳。 16 | 17 | 这个项目对于时间紧张的录友比较合适。 18 | 19 | **该项目满足一下特点**: 20 | 21 | * 代码量不大 22 | * 整体不难 23 | * 又有项目难点可说的 24 | * 可以较快学完 25 | 26 | 该缓存系统使用多个页面替换策略实现了**一个线程安全的缓存系统**: 27 | 28 | * LRU:最近最久未使用页面置换算法 29 | * LFU:最不经常使用页面置换算法 30 | * ARC:自适应替换缓存算法 31 | 32 | ## 做完本项目,你的收获 33 | 34 | 35 | * 掌握缓存的作用、层次结构与设计哲学,理解其在系统架构中的关键价值 36 | * 亲手实现并优化LRU、LFU、ARC算法,应对不同业务场景 37 | * 运用互斥锁、原子操作及缓存分片技术,保证多线程数据一致性与高性能 38 | * 通过分片降低锁竞争、预加载预热缓存,显著提升吞吐量与响应速度 39 | * 实践应对缓存穿透、击穿、雪崩的行业通用解决方案 40 | * 从数据结构设计、策略选择到性能评估,获得构建高性能中间件的完整经验 41 | 42 | ## 什么是缓存? 43 | 44 | 缓存是将高频访问的数据暂存到内存中,是加速数据访问的存储,降低延迟,提高吞吐率的利器。 45 | 46 | ## 为什么要实现缓存系统? 47 | 48 | 因缓存的使用相关需求,**通过牺牲一部分服务器内存,减少对磁盘或者数据库资源进行直接读写,可换取更快响应速度**。 49 | 50 | 尤其是处理高并发的场景,负责存储经常访问的数据,通过设计合理的缓存机制提高资源的访问效率。 51 | 52 | 由于服务器的内存是有限的,我们不能把所有数据都存放在内存中,因此需要一种机制来决定当使用内存超过一定标准时,应该删除哪些数据,这就涉及到缓存淘汰策略的选择。 53 | 54 | ## 实际应用场景 55 | 56 | 缓存策略在系统和实际业务开发过程中较为常见,下面我为大家列出一些使用了缓存策略的知名系统和组件: 57 | 58 | **Linux Kernel**: 使用 LRU 在内存管理中页面缓存(Page Cache),当物理内存不足时,系统会优先淘汰最近未使用的页面。 59 | 60 | **Android内存缓存**: Android的LRUCache类用于管理有限内存中的应用数据缓存。 61 | 62 | **Redis**:Redis 本身并不直接实现 LRU 缓存策略,但它提供了过期和淘汰机制。 63 | 64 | 在内存不足时,Redis 可以配置不同的淘汰策略,如 volatile-lru(对于设置了过期时间的键,使用 LRU 策略淘汰数据)。 65 | 66 | Redis 提供了 LFU 策略(从 4.0 版本开始)作为其内存驱逐策略之一,可以通过 maxmemory-policy 配置。 67 | 68 | **PostgreSQL** :在一些PostgreSQL的缓存拓展中实现了基于ARC的缓存机制 69 | 70 | ## 缓存系统项目精讲 71 | 72 | 该项目文档是[知识星球](https://programmercarl.com/other/kstar.html)录友专享的。 73 | 74 | 项目文档依然是将 「简历写法」给大家列出来了,大家学完就可以参考这个来写简历,分别给出普通写法和进阶写法: 75 | 76 |
77 | 78 | 做完该项目,面试中大概率会有哪些面试问题,以及如何回答,也列出好了,共27道。 79 | 80 |
81 | 82 | 文档中的项目面试题都掌握的话,这个项目在面试中基本没问题。 83 | 84 | 当然项目文档会对本项目代码做详细的讲解: 85 | 86 |
87 | 88 |
89 | 90 |
91 | 92 | 同时会对三个缓存策略做优劣对对比: 93 | 94 |
95 | 96 | 同时对缓存命中率做实验效果对比: 97 | 98 |
99 | 100 | ## 答疑 101 | 102 | 本项目在[知识星球](https://programmercarl.com/other/kstar.html)里为 文字专栏形式,大家不用担心,看不懂,星球里每个项目有专属答疑群,任何问题都可以在群里问,都会得到解答: 103 | 104 | ![](https://file1.kamacoder.com/i/web/2025-09-26_11-30-13.jpg) 105 | 106 | 107 | ## 获取本项目专栏 108 | 109 | **本文档仅为星球内部专享,大家可以加入[知识星球](https://programmercarl.com/other/kstar.html)里获取,在星球置顶一** 110 | 111 | -------------------------------------------------------------------------------- /KArcCache/KArcLruPart.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "KArcCacheNode.h" 4 | #include 5 | #include 6 | 7 | namespace KamaCache 8 | { 9 | 10 | template 11 | class ArcLruPart 12 | { 13 | public: 14 | using NodeType = ArcNode; 15 | using NodePtr = std::shared_ptr; 16 | using NodeMap = std::unordered_map; 17 | 18 | explicit ArcLruPart(size_t capacity, size_t transformThreshold) 19 | : capacity_(capacity) 20 | , ghostCapacity_(capacity) 21 | , transformThreshold_(transformThreshold) 22 | { 23 | initializeLists(); 24 | } 25 | 26 | bool put(Key key, Value value) 27 | { 28 | if (capacity_ == 0) return false; 29 | 30 | std::lock_guard lock(mutex_); 31 | auto it = mainCache_.find(key); 32 | if (it != mainCache_.end()) 33 | { 34 | return updateExistingNode(it->second, value); 35 | } 36 | return addNewNode(key, value); 37 | } 38 | 39 | bool get(Key key, Value& value, bool& shouldTransform) 40 | { 41 | std::lock_guard lock(mutex_); 42 | auto it = mainCache_.find(key); 43 | if (it != mainCache_.end()) 44 | { 45 | shouldTransform = updateNodeAccess(it->second); 46 | value = it->second->getValue(); 47 | return true; 48 | } 49 | return false; 50 | } 51 | 52 | bool checkGhost(Key key) 53 | { 54 | auto it = ghostCache_.find(key); 55 | if (it != ghostCache_.end()) { 56 | removeFromGhost(it->second); 57 | ghostCache_.erase(it); 58 | return true; 59 | } 60 | return false; 61 | } 62 | 63 | void increaseCapacity() { ++capacity_; } 64 | 65 | bool decreaseCapacity() 66 | { 67 | if (capacity_ <= 0) return false; 68 | if (mainCache_.size() == capacity_) { 69 | evictLeastRecent(); 70 | } 71 | --capacity_; 72 | return true; 73 | } 74 | 75 | private: 76 | void initializeLists() 77 | { 78 | mainHead_ = std::make_shared(); 79 | mainTail_ = std::make_shared(); 80 | mainHead_->next_ = mainTail_; 81 | mainTail_->prev_ = mainHead_; 82 | 83 | ghostHead_ = std::make_shared(); 84 | ghostTail_ = std::make_shared(); 85 | ghostHead_->next_ = ghostTail_; 86 | ghostTail_->prev_ = ghostHead_; 87 | } 88 | 89 | bool updateExistingNode(NodePtr node, const Value& value) 90 | { 91 | node->setValue(value); 92 | moveToFront(node); 93 | return true; 94 | } 95 | 96 | bool addNewNode(const Key& key, const Value& value) 97 | { 98 | if (mainCache_.size() >= capacity_) 99 | { 100 | evictLeastRecent(); // 驱逐最近最少访问 101 | } 102 | 103 | NodePtr newNode = std::make_shared(key, value); 104 | mainCache_[key] = newNode; 105 | addToFront(newNode); 106 | return true; 107 | } 108 | 109 | bool updateNodeAccess(NodePtr node) 110 | { 111 | moveToFront(node); 112 | node->incrementAccessCount(); 113 | return node->getAccessCount() >= transformThreshold_; 114 | } 115 | 116 | void moveToFront(NodePtr node) 117 | { 118 | // 先从当前位置移除 119 | if (!node->prev_.expired() && node->next_) { 120 | auto prev = node->prev_.lock(); 121 | prev->next_ = node->next_; 122 | node->next_->prev_ = node->prev_; 123 | node->next_ = nullptr; // 清空指针,防止悬垂引用 124 | } 125 | 126 | // 添加到头部 127 | addToFront(node); 128 | } 129 | 130 | void addToFront(NodePtr node) 131 | { 132 | node->next_ = mainHead_->next_; 133 | node->prev_ = mainHead_; 134 | mainHead_->next_->prev_ = node; 135 | mainHead_->next_ = node; 136 | } 137 | 138 | void evictLeastRecent() 139 | { 140 | NodePtr leastRecent = mainTail_->prev_.lock(); 141 | if (!leastRecent || leastRecent == mainHead_) 142 | return; 143 | 144 | // 从主链表中移除 145 | removeFromMain(leastRecent); 146 | 147 | // 添加到幽灵缓存 148 | if (ghostCache_.size() >= ghostCapacity_) 149 | { 150 | removeOldestGhost(); 151 | } 152 | addToGhost(leastRecent); 153 | 154 | // 从主缓存映射中移除 155 | mainCache_.erase(leastRecent->getKey()); 156 | } 157 | 158 | void removeFromMain(NodePtr node) 159 | { 160 | if (!node->prev_.expired() && node->next_) { 161 | auto prev = node->prev_.lock(); 162 | prev->next_ = node->next_; 163 | node->next_->prev_ = node->prev_; 164 | node->next_ = nullptr; // 清空指针,防止悬垂引用 165 | } 166 | } 167 | 168 | void removeFromGhost(NodePtr node) 169 | { 170 | if (!node->prev_.expired() && node->next_) { 171 | auto prev = node->prev_.lock(); 172 | prev->next_ = node->next_; 173 | node->next_->prev_ = node->prev_; 174 | node->next_ = nullptr; // 清空指针,防止悬垂引用 175 | } 176 | } 177 | 178 | void addToGhost(NodePtr node) 179 | { 180 | // 重置节点的访问计数 181 | node->accessCount_ = 1; 182 | 183 | // 添加到幽灵缓存的头部 184 | node->next_ = ghostHead_->next_; 185 | node->prev_ = ghostHead_; 186 | ghostHead_->next_->prev_ = node; 187 | ghostHead_->next_ = node; 188 | 189 | // 添加到幽灵缓存映射 190 | ghostCache_[node->getKey()] = node; 191 | } 192 | 193 | void removeOldestGhost() 194 | { 195 | // 使用lock()方法,并添加null检查 196 | NodePtr oldestGhost = ghostTail_->prev_.lock(); 197 | if (!oldestGhost || oldestGhost == ghostHead_) 198 | return; 199 | 200 | removeFromGhost(oldestGhost); 201 | ghostCache_.erase(oldestGhost->getKey()); 202 | } 203 | 204 | 205 | private: 206 | size_t capacity_; 207 | size_t ghostCapacity_; 208 | size_t transformThreshold_; // 转换门槛值 209 | std::mutex mutex_; 210 | 211 | NodeMap mainCache_; // key -> ArcNode 212 | NodeMap ghostCache_; 213 | 214 | // 主链表 215 | NodePtr mainHead_; 216 | NodePtr mainTail_; 217 | // 淘汰链表 218 | NodePtr ghostHead_; 219 | NodePtr ghostTail_; 220 | }; 221 | 222 | } // namespace KamaCache -------------------------------------------------------------------------------- /KArcCache/KArcLfuPart.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "KArcCacheNode.h" 4 | #include 5 | #include 6 | #include 7 | 8 | namespace KamaCache 9 | { 10 | 11 | template 12 | class ArcLfuPart 13 | { 14 | public: 15 | using NodeType = ArcNode; 16 | using NodePtr = std::shared_ptr; 17 | using NodeMap = std::unordered_map; 18 | using FreqMap = std::map>; 19 | 20 | explicit ArcLfuPart(size_t capacity, size_t transformThreshold) 21 | : capacity_(capacity) 22 | , ghostCapacity_(capacity) 23 | , transformThreshold_(transformThreshold) 24 | , minFreq_(0) 25 | { 26 | initializeLists(); 27 | } 28 | 29 | bool put(Key key, Value value) 30 | { 31 | if (capacity_ == 0) 32 | return false; 33 | 34 | std::lock_guard lock(mutex_); 35 | auto it = mainCache_.find(key); 36 | if (it != mainCache_.end()) 37 | { 38 | return updateExistingNode(it->second, value); 39 | } 40 | return addNewNode(key, value); 41 | } 42 | 43 | bool get(Key key, Value& value) 44 | { 45 | std::lock_guard lock(mutex_); 46 | auto it = mainCache_.find(key); 47 | if (it != mainCache_.end()) 48 | { 49 | updateNodeFrequency(it->second); 50 | value = it->second->getValue(); 51 | return true; 52 | } 53 | return false; 54 | } 55 | 56 | bool contain(Key key) 57 | { 58 | return mainCache_.find(key) != mainCache_.end(); 59 | } 60 | 61 | bool checkGhost(Key key) 62 | { 63 | auto it = ghostCache_.find(key); 64 | if (it != ghostCache_.end()) 65 | { 66 | removeFromGhost(it->second); 67 | ghostCache_.erase(it); 68 | return true; 69 | } 70 | return false; 71 | } 72 | 73 | void increaseCapacity() { ++capacity_; } 74 | 75 | bool decreaseCapacity() 76 | { 77 | if (capacity_ <= 0) return false; 78 | if (mainCache_.size() == capacity_) 79 | { 80 | evictLeastFrequent(); 81 | } 82 | --capacity_; 83 | return true; 84 | } 85 | 86 | private: 87 | void initializeLists() 88 | { 89 | ghostHead_ = std::make_shared(); 90 | ghostTail_ = std::make_shared(); 91 | ghostHead_->next_ = ghostTail_; 92 | ghostTail_->prev_ = ghostHead_; 93 | } 94 | 95 | bool updateExistingNode(NodePtr node, const Value& value) 96 | { 97 | node->setValue(value); 98 | updateNodeFrequency(node); 99 | return true; 100 | } 101 | 102 | bool addNewNode(const Key& key, const Value& value) 103 | { 104 | if (mainCache_.size() >= capacity_) 105 | { 106 | evictLeastFrequent(); 107 | } 108 | 109 | NodePtr newNode = std::make_shared(key, value); 110 | mainCache_[key] = newNode; 111 | 112 | // 将新节点添加到频率为1的列表中 113 | if (freqMap_.find(1) == freqMap_.end()) 114 | { 115 | freqMap_[1] = std::list(); 116 | } 117 | freqMap_[1].push_back(newNode); 118 | minFreq_ = 1; 119 | 120 | return true; 121 | } 122 | 123 | void updateNodeFrequency(NodePtr node) 124 | { 125 | size_t oldFreq = node->getAccessCount(); 126 | node->incrementAccessCount(); 127 | size_t newFreq = node->getAccessCount(); 128 | 129 | // 从旧频率列表中移除 130 | auto& oldList = freqMap_[oldFreq]; 131 | oldList.remove(node); 132 | if (oldList.empty()) 133 | { 134 | freqMap_.erase(oldFreq); 135 | if (oldFreq == minFreq_) 136 | { 137 | minFreq_ = newFreq; 138 | } 139 | } 140 | 141 | // 添加到新频率列表 142 | if (freqMap_.find(newFreq) == freqMap_.end()) 143 | { 144 | freqMap_[newFreq] = std::list(); 145 | } 146 | freqMap_[newFreq].push_back(node); 147 | } 148 | 149 | void evictLeastFrequent() 150 | { 151 | if (freqMap_.empty()) 152 | return; 153 | 154 | // 获取最小频率的列表 155 | auto& minFreqList = freqMap_[minFreq_]; 156 | if (minFreqList.empty()) 157 | return; 158 | 159 | // 移除最少使用的节点 160 | NodePtr leastNode = minFreqList.front(); 161 | minFreqList.pop_front(); 162 | 163 | // 如果该频率的列表为空,则删除该频率项 164 | if (minFreqList.empty()) 165 | { 166 | freqMap_.erase(minFreq_); 167 | // 更新最小频率 168 | if (!freqMap_.empty()) 169 | { 170 | minFreq_ = freqMap_.begin()->first; 171 | } 172 | } 173 | 174 | // 将节点移到幽灵缓存 175 | if (ghostCache_.size() >= ghostCapacity_) 176 | { 177 | removeOldestGhost(); 178 | } 179 | addToGhost(leastNode); 180 | 181 | // 从主缓存中移除 182 | mainCache_.erase(leastNode->getKey()); 183 | } 184 | 185 | void removeFromGhost(NodePtr node) 186 | { 187 | if (!node->prev_.expired() && node->next_) { 188 | auto prev = node->prev_.lock(); 189 | prev->next_ = node->next_; 190 | node->next_->prev_ = node->prev_; 191 | node->next_ = nullptr; // 清空指针,防止悬垂引用 192 | } 193 | } 194 | 195 | void addToGhost(NodePtr node) 196 | { 197 | node->next_ = ghostTail_; 198 | node->prev_ = ghostTail_->prev_; 199 | if (!ghostTail_->prev_.expired()) { 200 | ghostTail_->prev_.lock()->next_ = node; 201 | } 202 | ghostTail_->prev_ = node; 203 | ghostCache_[node->getKey()] = node; 204 | } 205 | 206 | void removeOldestGhost() 207 | { 208 | NodePtr oldestGhost = ghostHead_->next_; 209 | if (oldestGhost != ghostTail_) 210 | { 211 | removeFromGhost(oldestGhost); 212 | ghostCache_.erase(oldestGhost->getKey()); 213 | } 214 | } 215 | 216 | private: 217 | size_t capacity_; 218 | size_t ghostCapacity_; 219 | size_t transformThreshold_; 220 | size_t minFreq_; 221 | std::mutex mutex_; 222 | 223 | NodeMap mainCache_; 224 | NodeMap ghostCache_; 225 | FreqMap freqMap_; 226 | 227 | NodePtr ghostHead_; 228 | NodePtr ghostTail_; 229 | }; 230 | 231 | } // namespace KamaCache -------------------------------------------------------------------------------- /KLruCache.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "KICachePolicy.h" 10 | 11 | namespace KamaCache 12 | { 13 | 14 | // 前向声明 15 | template class KLruCache; 16 | 17 | template 18 | class LruNode 19 | { 20 | private: 21 | Key key_; 22 | Value value_; 23 | size_t accessCount_; // 访问次数 24 | std::weak_ptr> prev_; // 改为weak_ptr打破循环引用 25 | std::shared_ptr> next_; 26 | 27 | public: 28 | LruNode(Key key, Value value) 29 | : key_(key) 30 | , value_(value) 31 | , accessCount_(1) 32 | {} 33 | 34 | // 提供必要的访问器 35 | Key getKey() const { return key_; } 36 | Value getValue() const { return value_; } 37 | void setValue(const Value& value) { value_ = value; } 38 | size_t getAccessCount() const { return accessCount_; } 39 | void incrementAccessCount() { ++accessCount_; } 40 | 41 | friend class KLruCache; 42 | }; 43 | 44 | 45 | template 46 | class KLruCache : public KICachePolicy 47 | { 48 | public: 49 | using LruNodeType = LruNode; 50 | using NodePtr = std::shared_ptr; 51 | using NodeMap = std::unordered_map; 52 | 53 | KLruCache(int capacity) 54 | : capacity_(capacity) 55 | { 56 | initializeList(); 57 | } 58 | 59 | ~KLruCache() override = default; 60 | 61 | // 添加缓存 62 | void put(Key key, Value value) override 63 | { 64 | if (capacity_ <= 0) 65 | return; 66 | 67 | std::lock_guard lock(mutex_); 68 | auto it = nodeMap_.find(key); 69 | if (it != nodeMap_.end()) 70 | { 71 | // 如果在当前容器中,则更新value,并调用get方法,代表该数据刚被访问 72 | updateExistingNode(it->second, value); 73 | return ; 74 | } 75 | 76 | addNewNode(key, value); 77 | } 78 | 79 | bool get(Key key, Value& value) override 80 | { 81 | std::lock_guard lock(mutex_); 82 | auto it = nodeMap_.find(key); 83 | if (it != nodeMap_.end()) 84 | { 85 | moveToMostRecent(it->second); 86 | value = it->second->getValue(); 87 | return true; 88 | } 89 | return false; 90 | } 91 | 92 | Value get(Key key) override 93 | { 94 | Value value{}; 95 | // memset(&value, 0, sizeof(value)); // memset 是按字节设置内存的,对于复杂类型(如 string)使用 memset 可能会破坏对象的内部结构 96 | get(key, value); 97 | return value; 98 | } 99 | 100 | // 删除指定元素 101 | void remove(Key key) 102 | { 103 | std::lock_guard lock(mutex_); 104 | auto it = nodeMap_.find(key); 105 | if (it != nodeMap_.end()) 106 | { 107 | removeNode(it->second); 108 | nodeMap_.erase(it); 109 | } 110 | } 111 | 112 | private: 113 | void initializeList() 114 | { 115 | // 创建首尾虚拟节点 116 | dummyHead_ = std::make_shared(Key(), Value()); 117 | dummyTail_ = std::make_shared(Key(), Value()); 118 | dummyHead_->next_ = dummyTail_; 119 | dummyTail_->prev_ = dummyHead_; 120 | } 121 | 122 | void updateExistingNode(NodePtr node, const Value& value) 123 | { 124 | node->setValue(value); 125 | moveToMostRecent(node); 126 | } 127 | 128 | void addNewNode(const Key& key, const Value& value) 129 | { 130 | if (nodeMap_.size() >= capacity_) 131 | { 132 | evictLeastRecent(); 133 | } 134 | 135 | NodePtr newNode = std::make_shared(key, value); 136 | insertNode(newNode); 137 | nodeMap_[key] = newNode; 138 | } 139 | 140 | // 将该节点移动到最新的位置 141 | void moveToMostRecent(NodePtr node) 142 | { 143 | removeNode(node); 144 | insertNode(node); 145 | } 146 | 147 | void removeNode(NodePtr node) 148 | { 149 | if(!node->prev_.expired() && node->next_) 150 | { 151 | auto prev = node->prev_.lock(); // 使用lock()获取shared_ptr 152 | prev->next_ = node->next_; 153 | node->next_->prev_ = prev; 154 | node->next_ = nullptr; // 清空next_指针,彻底断开节点与链表的连接 155 | } 156 | } 157 | 158 | // 从尾部插入结点 159 | void insertNode(NodePtr node) 160 | { 161 | node->next_ = dummyTail_; 162 | node->prev_ = dummyTail_->prev_; 163 | dummyTail_->prev_.lock()->next_ = node; // 使用lock()获取shared_ptr 164 | dummyTail_->prev_ = node; 165 | } 166 | 167 | // 驱逐最近最少访问 168 | void evictLeastRecent() 169 | { 170 | NodePtr leastRecent = dummyHead_->next_; 171 | removeNode(leastRecent); 172 | nodeMap_.erase(leastRecent->getKey()); 173 | } 174 | 175 | private: 176 | int capacity_; // 缓存容量 177 | NodeMap nodeMap_; // key -> Node 178 | std::mutex mutex_; 179 | NodePtr dummyHead_; // 虚拟头结点 180 | NodePtr dummyTail_; 181 | }; 182 | 183 | // LRU优化:Lru-k版本。 通过继承的方式进行再优化 184 | template 185 | class KLruKCache : public KLruCache 186 | { 187 | public: 188 | KLruKCache(int capacity, int historyCapacity, int k) 189 | : KLruCache(capacity) // 调用基类构造 190 | , historyList_(std::make_unique>(historyCapacity)) 191 | , k_(k) 192 | {} 193 | 194 | Value get(Key key) 195 | { 196 | // 首先尝试从主缓存获取数据 197 | Value value{}; 198 | bool inMainCache = KLruCache::get(key, value); 199 | 200 | // 获取并更新访问历史计数 201 | size_t historyCount = historyList_->get(key); 202 | historyCount++; 203 | historyList_->put(key, historyCount); 204 | 205 | // 如果数据在主缓存中,直接返回 206 | if (inMainCache) 207 | { 208 | return value; 209 | } 210 | 211 | // 如果数据不在主缓存,但访问次数达到了k次 212 | if (historyCount >= k_) 213 | { 214 | // 检查是否有历史值记录 215 | auto it = historyValueMap_.find(key); 216 | if (it != historyValueMap_.end()) 217 | { 218 | // 有历史值,将其添加到主缓存 219 | Value storedValue = it->second; 220 | 221 | // 从历史记录移除 222 | historyList_->remove(key); 223 | historyValueMap_.erase(it); 224 | 225 | // 添加到主缓存 226 | KLruCache::put(key, storedValue); 227 | 228 | return storedValue; 229 | } 230 | // 没有历史值记录,无法添加到缓存,返回默认值 231 | } 232 | 233 | // 数据不在主缓存且不满足添加条件,返回默认值 234 | return value; 235 | } 236 | 237 | void put(Key key, Value value) 238 | { 239 | // 检查是否已在主缓存 240 | Value existingValue{}; 241 | bool inMainCache = KLruCache::get(key, existingValue); 242 | 243 | if (inMainCache) 244 | { 245 | // 已在主缓存,直接更新 246 | KLruCache::put(key, value); 247 | return; 248 | } 249 | 250 | // 获取并更新访问历史 251 | size_t historyCount = historyList_->get(key); 252 | historyCount++; 253 | historyList_->put(key, historyCount); 254 | 255 | // 保存值到历史记录映射,供后续get操作使用 256 | historyValueMap_[key] = value; 257 | 258 | // 检查是否达到k次访问阈值 259 | if (historyCount >= k_) 260 | { 261 | // 达到阈值,添加到主缓存 262 | historyList_->remove(key); 263 | historyValueMap_.erase(key); 264 | KLruCache::put(key, value); 265 | } 266 | } 267 | 268 | private: 269 | int k_; // 进入缓存队列的评判标准 270 | std::unique_ptr> historyList_; // 访问数据历史记录(value为访问次数) 271 | std::unordered_map historyValueMap_; // 存储未达到k次访问的数据值 272 | }; 273 | 274 | // lru优化:对lru进行分片,提高高并发使用的性能 275 | template 276 | class KHashLruCaches 277 | { 278 | public: 279 | KHashLruCaches(size_t capacity, int sliceNum) 280 | : capacity_(capacity) 281 | , sliceNum_(sliceNum > 0 ? sliceNum : std::thread::hardware_concurrency()) 282 | { 283 | size_t sliceSize = std::ceil(capacity / static_cast(sliceNum_)); // 获取每个分片的大小 284 | for (int i = 0; i < sliceNum_; ++i) 285 | { 286 | lruSliceCaches_.emplace_back(new KLruCache(sliceSize)); 287 | } 288 | } 289 | 290 | void put(Key key, Value value) 291 | { 292 | // 获取key的hash值,并计算出对应的分片索引 293 | size_t sliceIndex = Hash(key) % sliceNum_; 294 | lruSliceCaches_[sliceIndex]->put(key, value); 295 | } 296 | 297 | bool get(Key key, Value& value) 298 | { 299 | // 获取key的hash值,并计算出对应的分片索引 300 | size_t sliceIndex = Hash(key) % sliceNum_; 301 | return lruSliceCaches_[sliceIndex]->get(key, value); 302 | } 303 | 304 | Value get(Key key) 305 | { 306 | Value value; 307 | memset(&value, 0, sizeof(value)); 308 | get(key, value); 309 | return value; 310 | } 311 | 312 | private: 313 | // 将key转换为对应hash值 314 | size_t Hash(Key key) 315 | { 316 | std::hash hashFunc; 317 | return hashFunc(key); 318 | } 319 | 320 | private: 321 | size_t capacity_; // 总容量 322 | int sliceNum_; // 切片数量 323 | std::vector>> lruSliceCaches_; // 切片LRU缓存 324 | }; 325 | 326 | } // namespace KamaCache -------------------------------------------------------------------------------- /KLfuCache.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "KICachePolicy.h" 11 | 12 | namespace KamaCache 13 | { 14 | 15 | template class KLfuCache; 16 | 17 | template 18 | class FreqList 19 | { 20 | private: 21 | struct Node 22 | { 23 | int freq; // 访问频次 24 | Key key; 25 | Value value; 26 | std::weak_ptr pre; // 上一结点改为weak_ptr打破循环引用 27 | std::shared_ptr next; 28 | 29 | Node() 30 | : freq(1), next(nullptr) {} 31 | Node(Key key, Value value) 32 | : freq(1), key(key), value(value), next(nullptr) {} 33 | }; 34 | 35 | using NodePtr = std::shared_ptr; 36 | int freq_; // 访问频率 37 | NodePtr head_; // 假头结点 38 | NodePtr tail_; // 假尾结点 39 | 40 | public: 41 | explicit FreqList(int n) 42 | : freq_(n) 43 | { 44 | head_ = std::make_shared(); 45 | tail_ = std::make_shared(); 46 | head_->next = tail_; 47 | tail_->pre = head_; 48 | } 49 | 50 | bool isEmpty() const 51 | { 52 | return head_->next == tail_; 53 | } 54 | 55 | // 提那家结点管理方法 56 | void addNode(NodePtr node) 57 | { 58 | if (!node || !head_ || !tail_) 59 | return; 60 | 61 | node->pre = tail_->pre; 62 | node->next = tail_; 63 | tail_->pre.lock()->next = node; // 使用lock()获取shared_ptr 64 | tail_->pre = node; 65 | } 66 | 67 | void removeNode(NodePtr node) 68 | { 69 | if (!node || !head_ || !tail_) 70 | return; 71 | if (node->pre.expired() || !node->next) 72 | return; 73 | 74 | auto pre = node->pre.lock(); // 使用lock()获取shared_ptr 75 | pre->next = node->next; 76 | node->next->pre = pre; 77 | node->next = nullptr; // 确保显式置空next指针,彻底断开节点与链表的连接 78 | } 79 | 80 | NodePtr getFirstNode() const { return head_->next; } 81 | 82 | friend class KLfuCache; 83 | }; 84 | 85 | template 86 | class KLfuCache : public KICachePolicy 87 | { 88 | public: 89 | using Node = typename FreqList::Node; 90 | using NodePtr = std::shared_ptr; 91 | using NodeMap = std::unordered_map; 92 | 93 | KLfuCache(int capacity, int maxAverageNum = 1000000) 94 | : capacity_(capacity), minFreq_(INT8_MAX), maxAverageNum_(maxAverageNum), 95 | curAverageNum_(0), curTotalNum_(0) 96 | {} 97 | 98 | ~KLfuCache() override = default; 99 | 100 | void put(Key key, Value value) override 101 | { 102 | if (capacity_ == 0) 103 | return; 104 | 105 | std::lock_guard lock(mutex_); 106 | auto it = nodeMap_.find(key); 107 | if (it != nodeMap_.end()) 108 | { 109 | // 重置其value值 110 | it->second->value = value; 111 | // 找到了直接调整就好了,不用再去get中再找一遍,但其实影响不大 112 | getInternal(it->second, value); 113 | return; 114 | } 115 | 116 | putInternal(key, value); 117 | } 118 | 119 | // value值为传出参数 120 | bool get(Key key, Value& value) override 121 | { 122 | std::lock_guard lock(mutex_); 123 | auto it = nodeMap_.find(key); 124 | if (it != nodeMap_.end()) 125 | { 126 | getInternal(it->second, value); 127 | return true; 128 | } 129 | 130 | return false; 131 | } 132 | 133 | Value get(Key key) override 134 | { 135 | Value value; 136 | get(key, value); 137 | return value; 138 | } 139 | 140 | // 清空缓存,回收资源 141 | void purge() 142 | { 143 | nodeMap_.clear(); 144 | freqToFreqList_.clear(); 145 | } 146 | 147 | private: 148 | void putInternal(Key key, Value value); // 添加缓存 149 | void getInternal(NodePtr node, Value& value); // 获取缓存 150 | 151 | void kickOut(); // 移除缓存中的过期数据 152 | 153 | void removeFromFreqList(NodePtr node); // 从频率列表中移除节点 154 | void addToFreqList(NodePtr node); // 添加到频率列表 155 | 156 | void addFreqNum(); // 增加平均访问等频率 157 | void decreaseFreqNum(int num); // 减少平均访问等频率 158 | void handleOverMaxAverageNum(); // 处理当前平均访问频率超过上限的情况 159 | void updateMinFreq(); 160 | 161 | private: 162 | int capacity_; // 缓存容量 163 | int minFreq_; // 最小访问频次(用于找到最小访问频次结点) 164 | int maxAverageNum_; // 最大平均访问频次 165 | int curAverageNum_; // 当前平均访问频次 166 | int curTotalNum_; // 当前访问所有缓存次数总数 167 | std::mutex mutex_; // 互斥锁 168 | NodeMap nodeMap_; // key 到 缓存节点的映射 169 | std::unordered_map*> freqToFreqList_;// 访问频次到该频次链表的映射 170 | }; 171 | 172 | template 173 | void KLfuCache::getInternal(NodePtr node, Value& value) 174 | { 175 | // 找到之后需要将其从低访问频次的链表中删除,并且添加到+1的访问频次链表中, 176 | // 访问频次+1, 然后把value值返回 177 | value = node->value; 178 | // 从原有访问频次的链表中删除节点 179 | removeFromFreqList(node); 180 | node->freq++; 181 | addToFreqList(node); 182 | // 如果当前node的访问频次如果等于minFreq+1,并且其前驱链表为空,则说明 183 | // freqToFreqList_[node->freq - 1]链表因node的迁移已经空了,需要更新最小访问频次 184 | if (node->freq - 1 == minFreq_ && freqToFreqList_[node->freq - 1]->isEmpty()) 185 | minFreq_++; 186 | 187 | // 总访问频次和当前平均访问频次都随之增加 188 | addFreqNum(); 189 | } 190 | 191 | template 192 | void KLfuCache::putInternal(Key key, Value value) 193 | { 194 | // 如果不在缓存中,则需要判断缓存是否已满 195 | if (nodeMap_.size() == capacity_) 196 | { 197 | // 缓存已满,删除最不常访问的结点,更新当前平均访问频次和总访问频次 198 | kickOut(); 199 | } 200 | 201 | // 创建新结点,将新结点添加进入,更新最小访问频次 202 | NodePtr node = std::make_shared(key, value); 203 | nodeMap_[key] = node; 204 | addToFreqList(node); 205 | addFreqNum(); 206 | minFreq_ = std::min(minFreq_, 1); 207 | } 208 | 209 | template 210 | void KLfuCache::kickOut() 211 | { 212 | NodePtr node = freqToFreqList_[minFreq_]->getFirstNode(); 213 | removeFromFreqList(node); 214 | nodeMap_.erase(node->key); 215 | decreaseFreqNum(node->freq); 216 | } 217 | 218 | template 219 | void KLfuCache::removeFromFreqList(NodePtr node) 220 | { 221 | // 检查结点是否为空 222 | if (!node) 223 | return; 224 | 225 | auto freq = node->freq; 226 | freqToFreqList_[freq]->removeNode(node); 227 | } 228 | 229 | template 230 | void KLfuCache::addToFreqList(NodePtr node) 231 | { 232 | // 检查结点是否为空 233 | if (!node) 234 | return; 235 | 236 | // 添加进入相应的频次链表前需要判断该频次链表是否存在 237 | auto freq = node->freq; 238 | if (freqToFreqList_.find(node->freq) == freqToFreqList_.end()) 239 | { 240 | // 不存在则创建 241 | freqToFreqList_[node->freq] = new FreqList(node->freq); 242 | } 243 | 244 | freqToFreqList_[freq]->addNode(node); 245 | } 246 | 247 | template 248 | void KLfuCache::addFreqNum() 249 | { 250 | curTotalNum_++; 251 | if (nodeMap_.empty()) 252 | curAverageNum_ = 0; 253 | else 254 | curAverageNum_ = curTotalNum_ / nodeMap_.size(); 255 | 256 | if (curAverageNum_ > maxAverageNum_) 257 | { 258 | handleOverMaxAverageNum(); 259 | } 260 | } 261 | 262 | template 263 | void KLfuCache::decreaseFreqNum(int num) 264 | { 265 | // 减少平均访问频次和总访问频次 266 | curTotalNum_ -= num; 267 | if (nodeMap_.empty()) 268 | curAverageNum_ = 0; 269 | else 270 | curAverageNum_ = curTotalNum_ / nodeMap_.size(); 271 | } 272 | 273 | template 274 | void KLfuCache::handleOverMaxAverageNum() 275 | { 276 | if (nodeMap_.empty()) 277 | return; 278 | 279 | // 当前平均访问频次已经超过了最大平均访问频次,所有结点的访问频次- (maxAverageNum_ / 2) 280 | for (auto it = nodeMap_.begin(); it != nodeMap_.end(); ++it) 281 | { 282 | // 检查结点是否为空 283 | if (!it->second) 284 | continue; 285 | 286 | NodePtr node = it->second; 287 | 288 | // 先从当前频率列表中移除 289 | removeFromFreqList(node); 290 | 291 | // 减少频率 292 | node->freq -= maxAverageNum_ / 2; 293 | if (node->freq < 1) node->freq = 1; 294 | 295 | // 添加到新的频率列表 296 | addToFreqList(node); 297 | } 298 | 299 | // 更新最小频率 300 | updateMinFreq(); 301 | } 302 | 303 | template 304 | void KLfuCache::updateMinFreq() 305 | { 306 | minFreq_ = INT8_MAX; 307 | for (const auto& pair : freqToFreqList_) 308 | { 309 | if (pair.second && !pair.second->isEmpty()) 310 | { 311 | minFreq_ = std::min(minFreq_, pair.first); 312 | } 313 | } 314 | if (minFreq_ == INT8_MAX) 315 | minFreq_ = 1; 316 | } 317 | 318 | // 并没有牺牲空间换时间,他是把原有缓存大小进行了分片。 319 | template 320 | class KHashLfuCache 321 | { 322 | public: 323 | KHashLfuCache(size_t capacity, int sliceNum, int maxAverageNum = 10) 324 | : sliceNum_(sliceNum > 0 ? sliceNum : std::thread::hardware_concurrency()) 325 | , capacity_(capacity) 326 | { 327 | size_t sliceSize = std::ceil(capacity_ / static_cast(sliceNum_)); // 每个lfu分片的容量 328 | for (int i = 0; i < sliceNum_; ++i) 329 | { 330 | lfuSliceCaches_.emplace_back(new KLfuCache(sliceSize, maxAverageNum)); 331 | } 332 | } 333 | 334 | void put(Key key, Value value) 335 | { 336 | // 根据key找出对应的lfu分片 337 | size_t sliceIndex = Hash(key) % sliceNum_; 338 | lfuSliceCaches_[sliceIndex]->put(key, value); 339 | } 340 | 341 | bool get(Key key, Value& value) 342 | { 343 | // 根据key找出对应的lfu分片 344 | size_t sliceIndex = Hash(key) % sliceNum_; 345 | return lfuSliceCaches_[sliceIndex]->get(key, value); 346 | } 347 | 348 | Value get(Key key) 349 | { 350 | Value value; 351 | get(key, value); 352 | return value; 353 | } 354 | 355 | // 清除缓存 356 | void purge() 357 | { 358 | for (auto& lfuSliceCache : lfuSliceCaches_) 359 | { 360 | lfuSliceCache->purge(); 361 | } 362 | } 363 | 364 | private: 365 | // 将key计算成对应哈希值 366 | size_t Hash(Key key) 367 | { 368 | std::hash hashFunc; 369 | return hashFunc(key); 370 | } 371 | 372 | private: 373 | size_t capacity_; // 缓存总容量 374 | int sliceNum_; // 缓存分片数量 375 | std::vector>> lfuSliceCaches_; // 缓存lfu分片容器 376 | }; 377 | 378 | } // namespace KamaCache 379 | 380 | -------------------------------------------------------------------------------- /testAllCachePolicy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "KICachePolicy.h" 10 | #include "KLfuCache.h" 11 | #include "KLruCache.h" 12 | #include "KArcCache/KArcCache.h" 13 | 14 | class Timer { 15 | public: 16 | Timer() : start_(std::chrono::high_resolution_clock::now()) {} 17 | 18 | double elapsed() { 19 | auto now = std::chrono::high_resolution_clock::now(); 20 | return std::chrono::duration_cast(now - start_).count(); 21 | } 22 | 23 | private: 24 | std::chrono::time_point start_; 25 | }; 26 | 27 | // 辅助函数:打印结果 28 | void printResults(const std::string& testName, int capacity, 29 | const std::vector& get_operations, 30 | const std::vector& hits) { 31 | std::cout << "=== " << testName << " 结果汇总 ===" << std::endl; 32 | std::cout << "缓存大小: " << capacity << std::endl; 33 | 34 | // 假设对应的算法名称已在测试函数中定义 35 | std::vector names; 36 | if (hits.size() == 3) { 37 | names = {"LRU", "LFU", "ARC"}; 38 | } else if (hits.size() == 4) { 39 | names = {"LRU", "LFU", "ARC", "LRU-K"}; 40 | } else if (hits.size() == 5) { 41 | names = {"LRU", "LFU", "ARC", "LRU-K", "LFU-Aging"}; 42 | } 43 | 44 | for (size_t i = 0; i < hits.size(); ++i) { 45 | double hitRate = 100.0 * hits[i] / get_operations[i]; 46 | std::cout << (i < names.size() ? names[i] : "Algorithm " + std::to_string(i+1)) 47 | << " - 命中率: " << std::fixed << std::setprecision(2) 48 | << hitRate << "% "; 49 | // 添加具体命中次数和总操作次数 50 | std::cout << "(" << hits[i] << "/" << get_operations[i] << ")" << std::endl; 51 | } 52 | 53 | std::cout << std::endl; // 添加空行,使输出更清晰 54 | } 55 | 56 | void testHotDataAccess() { 57 | std::cout << "\n=== 测试场景1:热点数据访问测试 ===" << std::endl; 58 | 59 | const int CAPACITY = 20; // 缓存容量 60 | const int OPERATIONS = 500000; // 总操作次数 61 | const int HOT_KEYS = 20; // 热点数据数量 62 | const int COLD_KEYS = 5000; // 冷数据数量 63 | 64 | KamaCache::KLruCache lru(CAPACITY); 65 | KamaCache::KLfuCache lfu(CAPACITY); 66 | KamaCache::KArcCache arc(CAPACITY); 67 | // 为LRU-K设置合适的参数: 68 | // - 主缓存容量与其他算法相同 69 | // - 历史记录容量设为可能访问的所有键数量 70 | // - k=2表示数据被访问2次后才会进入缓存,适合区分热点和冷数据 71 | KamaCache::KLruKCache lruk(CAPACITY, HOT_KEYS + COLD_KEYS, 2); 72 | KamaCache::KLfuCache lfuAging(CAPACITY, 20000); 73 | 74 | std::random_device rd; 75 | std::mt19937 gen(rd()); 76 | 77 | // 基类指针指向派生类对象,添加LFU-Aging 78 | std::array*, 5> caches = {&lru, &lfu, &arc, &lruk, &lfuAging}; 79 | std::vector hits(5, 0); 80 | std::vector get_operations(5, 0); 81 | std::vector names = {"LRU", "LFU", "ARC", "LRU-K", "LFU-Aging"}; 82 | 83 | // 为所有的缓存对象进行相同的操作序列测试 84 | for (int i = 0; i < caches.size(); ++i) { 85 | // 先预热缓存,插入一些数据 86 | for (int key = 0; key < HOT_KEYS; ++key) { 87 | std::string value = "value" + std::to_string(key); 88 | caches[i]->put(key, value); 89 | } 90 | 91 | // 交替进行put和get操作,模拟真实场景 92 | for (int op = 0; op < OPERATIONS; ++op) { 93 | // 大多数缓存系统中读操作比写操作频繁 94 | // 所以设置30%概率进行写操作 95 | bool isPut = (gen() % 100 < 30); 96 | int key; 97 | 98 | // 70%概率访问热点数据,30%概率访问冷数据 99 | if (gen() % 100 < 70) { 100 | key = gen() % HOT_KEYS; // 热点数据 101 | } else { 102 | key = HOT_KEYS + (gen() % COLD_KEYS); // 冷数据 103 | } 104 | 105 | if (isPut) { 106 | // 执行put操作 107 | std::string value = "value" + std::to_string(key) + "_v" + std::to_string(op % 100); 108 | caches[i]->put(key, value); 109 | } else { 110 | // 执行get操作并记录命中情况 111 | std::string result; 112 | get_operations[i]++; 113 | if (caches[i]->get(key, result)) { 114 | hits[i]++; 115 | } 116 | } 117 | } 118 | } 119 | 120 | // 打印测试结果 121 | printResults("热点数据访问测试", CAPACITY, get_operations, hits); 122 | } 123 | 124 | void testLoopPattern() { 125 | std::cout << "\n=== 测试场景2:循环扫描测试 ===" << std::endl; 126 | 127 | const int CAPACITY = 50; // 缓存容量 128 | const int LOOP_SIZE = 500; // 循环范围大小 129 | const int OPERATIONS = 200000; // 总操作次数 130 | 131 | KamaCache::KLruCache lru(CAPACITY); 132 | KamaCache::KLfuCache lfu(CAPACITY); 133 | KamaCache::KArcCache arc(CAPACITY); 134 | // 为LRU-K设置合适的参数: 135 | // - 历史记录容量设为总循环大小的两倍,覆盖范围内和范围外的数据 136 | // - k=2,对于循环访问,这是一个合理的阈值 137 | KamaCache::KLruKCache lruk(CAPACITY, LOOP_SIZE * 2, 2); 138 | KamaCache::KLfuCache lfuAging(CAPACITY, 3000); 139 | 140 | std::array*, 5> caches = {&lru, &lfu, &arc, &lruk, &lfuAging}; 141 | std::vector hits(5, 0); 142 | std::vector get_operations(5, 0); 143 | std::vector names = {"LRU", "LFU", "ARC", "LRU-K", "LFU-Aging"}; 144 | 145 | std::random_device rd; 146 | std::mt19937 gen(rd()); 147 | 148 | // 为每种缓存算法运行相同的测试 149 | for (int i = 0; i < caches.size(); ++i) { 150 | // 先预热一部分数据(只加载20%的数据) 151 | for (int key = 0; key < LOOP_SIZE / 5; ++key) { 152 | std::string value = "loop" + std::to_string(key); 153 | caches[i]->put(key, value); 154 | } 155 | 156 | // 设置循环扫描的当前位置 157 | int current_pos = 0; 158 | 159 | // 交替进行读写操作,模拟真实场景 160 | for (int op = 0; op < OPERATIONS; ++op) { 161 | // 20%概率是写操作,80%概率是读操作 162 | bool isPut = (gen() % 100 < 20); 163 | int key; 164 | 165 | // 按照不同模式选择键 166 | if (op % 100 < 60) { // 60%顺序扫描 167 | key = current_pos; 168 | current_pos = (current_pos + 1) % LOOP_SIZE; 169 | } else if (op % 100 < 90) { // 30%随机跳跃 170 | key = gen() % LOOP_SIZE; 171 | } else { // 10%访问范围外数据 172 | key = LOOP_SIZE + (gen() % LOOP_SIZE); 173 | } 174 | 175 | if (isPut) { 176 | // 执行put操作,更新数据 177 | std::string value = "loop" + std::to_string(key) + "_v" + std::to_string(op % 100); 178 | caches[i]->put(key, value); 179 | } else { 180 | // 执行get操作并记录命中情况 181 | std::string result; 182 | get_operations[i]++; 183 | if (caches[i]->get(key, result)) { 184 | hits[i]++; 185 | } 186 | } 187 | } 188 | } 189 | 190 | printResults("循环扫描测试", CAPACITY, get_operations, hits); 191 | } 192 | 193 | void testWorkloadShift() { 194 | std::cout << "\n=== 测试场景3:工作负载剧烈变化测试 ===" << std::endl; 195 | 196 | const int CAPACITY = 30; // 缓存容量 197 | const int OPERATIONS = 80000; // 总操作次数 198 | const int PHASE_LENGTH = OPERATIONS / 5; // 每个阶段的长度 199 | 200 | KamaCache::KLruCache lru(CAPACITY); 201 | KamaCache::KLfuCache lfu(CAPACITY); 202 | KamaCache::KArcCache arc(CAPACITY); 203 | KamaCache::KLruKCache lruk(CAPACITY, 500, 2); 204 | KamaCache::KLfuCache lfuAging(CAPACITY, 10000); 205 | 206 | std::random_device rd; 207 | std::mt19937 gen(rd()); 208 | std::array*, 5> caches = {&lru, &lfu, &arc, &lruk, &lfuAging}; 209 | std::vector hits(5, 0); 210 | std::vector get_operations(5, 0); 211 | std::vector names = {"LRU", "LFU", "ARC", "LRU-K", "LFU-Aging"}; 212 | 213 | // 为每种缓存算法运行相同的测试 214 | for (int i = 0; i < caches.size(); ++i) { 215 | // 先预热缓存,只插入少量初始数据 216 | for (int key = 0; key < 30; ++key) { 217 | std::string value = "init" + std::to_string(key); 218 | caches[i]->put(key, value); 219 | } 220 | 221 | // 进行多阶段测试,每个阶段有不同的访问模式 222 | for (int op = 0; op < OPERATIONS; ++op) { 223 | // 确定当前阶段 224 | int phase = op / PHASE_LENGTH; 225 | 226 | // 每个阶段的读写比例不同 227 | int putProbability; 228 | switch (phase) { 229 | case 0: putProbability = 15; break; // 阶段1: 热点访问,15%写入更合理 230 | case 1: putProbability = 30; break; // 阶段2: 大范围随机,写比例为30% 231 | case 2: putProbability = 10; break; // 阶段3: 顺序扫描,10%写入保持不变 232 | case 3: putProbability = 25; break; // 阶段4: 局部性随机,微调为25% 233 | case 4: putProbability = 20; break; // 阶段5: 混合访问,调整为20% 234 | default: putProbability = 20; 235 | } 236 | 237 | // 确定是读还是写操作 238 | bool isPut = (gen() % 100 < putProbability); 239 | 240 | // 根据不同阶段选择不同的访问模式生成key - 优化后的访问范围 241 | int key; 242 | if (op < PHASE_LENGTH) { // 阶段1: 热点访问 - 热点数量5,使热点更集中 243 | key = gen() % 5; 244 | } else if (op < PHASE_LENGTH * 2) { // 阶段2: 大范围随机 - 范围400,更适合30大小的缓存 245 | key = gen() % 400; 246 | } else if (op < PHASE_LENGTH * 3) { // 阶段3: 顺序扫描 - 保持100个键 247 | key = (op - PHASE_LENGTH * 2) % 100; 248 | } else if (op < PHASE_LENGTH * 4) { // 阶段4: 局部性随机 - 优化局部性区域大小 249 | // 产生5个局部区域,每个区域大小为15个键,与缓存大小20接近但略小 250 | int locality = (op / 800) % 5; // 调整为5个局部区域 251 | key = locality * 15 + (gen() % 15); // 每区域15个键 252 | } else { // 阶段5: 混合访问 - 增加热点访问比例 253 | int r = gen() % 100; 254 | if (r < 40) { // 40%概率访问热点(从30%增加) 255 | key = gen() % 5; // 5个热点键 256 | } else if (r < 70) { // 30%概率访问中等范围 257 | key = 5 + (gen() % 45); // 缩小中等范围为50个键 258 | } else { // 30%概率访问大范围(从40%减少) 259 | key = 50 + (gen() % 350); // 大范围也相应缩小 260 | } 261 | } 262 | 263 | if (isPut) { 264 | // 执行写操作 265 | std::string value = "value" + std::to_string(key) + "_p" + std::to_string(phase); 266 | caches[i]->put(key, value); 267 | } else { 268 | // 执行读操作并记录命中情况 269 | std::string result; 270 | get_operations[i]++; 271 | if (caches[i]->get(key, result)) { 272 | hits[i]++; 273 | } 274 | } 275 | } 276 | } 277 | 278 | printResults("工作负载剧烈变化测试", CAPACITY, get_operations, hits); 279 | } 280 | 281 | int main() { 282 | testHotDataAccess(); 283 | testLoopPattern(); 284 | testWorkloadShift(); 285 | return 0; 286 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------