https://github.com/hengxin666/hxcache
提供最低C++11即可使用的线程安全的LRU、LFU,只需要单头文件; 只依赖于STL, 支持原地构造和透明查找. | Providing thread-safe LRU, LFU with the lowest C++11 usage, only requires a single header file; depends only on STL, supports in-place construction and transparent lookup.
https://github.com/hengxin666/hxcache
cache cpp11 lfu-cache lru-cache
Last synced: 4 months ago
JSON representation
提供最低C++11即可使用的线程安全的LRU、LFU,只需要单头文件; 只依赖于STL, 支持原地构造和透明查找. | Providing thread-safe LRU, LFU with the lowest C++11 usage, only requires a single header file; depends only on STL, supports in-place construction and transparent lookup.
- Host: GitHub
- URL: https://github.com/hengxin666/hxcache
- Owner: HengXin666
- License: apache-2.0
- Created: 2024-10-19T10:00:53.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-10-21T14:16:24.000Z (over 1 year ago)
- Last Synced: 2025-03-29T00:24:19.324Z (about 1 year ago)
- Topics: cache, cpp11, lfu-cache, lru-cache
- Language: C++
- Homepage:
- Size: 17.6 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
HXCache
实现了线程安全的LRU、LFU,只需要单头文件; 只依赖于STL, 支持原地构造和透明查找.
本项目是从 [HXNet](https://github.com/HengXin666/HXNet) 中分出来的(*并且特化支持C++20以下的内容*), 专门用于提供LRU、LFU等Cache.
## 构建要求
- 最低 C++11 (因为STL没有读写锁, 所以使用`std::mutex`)
- C++14 此时支持`透明查找`(`contains`) (因为STL没有纯的读写锁, 所以使用`std::shared_timed_mutex`, 不过我相信在不使用定时的情况下, 性能损耗为 0)
- C++17 (性能完全体, 使用`std::shared_mutex`)
## 示例
- [LRUCache/LFUCache的示例](examples/CacheTest.cpp)
下面是一个简单的示例, LFU和LRU的的API是一样的.
```C++
#include
int main() {
HX::ThreadSafeLFUCache cache(2); // capacity = 2
cache.insert(123, "This 123~");
cache.emplace(456, "This 456~"); // 原地构造
const std::string& str = cache.get(123);
std::cout << str << '\n'; // This 123~
std::cout << "cache size = " << cache.size() << '\n'; // 2
cache.clear();
std::cout << "cache size = " << cache.size() << '\n'; // 0
return 0;
// 注意, 如果是c++14及其以后
// 如果key是std::string,
// 那么当我们使用 cache.get("KeyData"); 的时候,
// 使用的是`透明查找`! 不会原地调用`std::string`的构造函数把`const char *`
// 构造后, 再传参! 而是直接使用
// 例如: XxxCache::get(const char (&key)[8]) 这个方法
}
```