答案:基于哈希表和双向链表实现线程安全的LRU缓存,使用std::mutex保证get和put操作的原子性,通过splice维护访问顺序,并在超出容量时淘汰尾部元素。

实现一个线程安全的LRU(Least Recently Used)缓存是C++并发编程中常见的需求,尤其在高并发服务场景下,如数据库连接池、HTTP响应缓存等。关键在于保证缓存操作(get、put)的原子性,并兼顾性能与正确性。
标准LRU通常结合哈希表和双向链表:
每次get或put操作后,对应节点需移动到链表头部表示“最近使用”。
为避免数据竞争,必须对共享数据加锁。常见做法是使用互斥锁(mutex)保护整个缓存结构。
立即学习“C++免费学习笔记(深入)”;
注意:细粒度锁虽然能提升并发性能,但会显著增加复杂度,一般推荐使用单个mutex配合条件变量(如需要阻塞等待空间)。示例中使用std::mutex和std::lock_guard确保操作的原子性。
以下是一个简洁、线程安全的LRU缓存实现:
#include <unordered_map>
#include <list>
#include <mutex>
template<typename K, typename V>
class ThreadSafeLRUCache {
private:
size_t capacity;
std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> cache_map;
std::list<std::pair<K, V>> cache_list;
mutable std::mutex mtx;
public:
explicit ThreadSafeLRUCache(size_t cap) : capacity(cap) {}
bool get(const K& key, V& value) {
std::lock_guard<std::mutex> lock(mtx);
auto it = cache_map.find(key);
if (it == cache_map.end()) {
return false; // 未命中
}
// 将命中节点移到链表头部
cache_list.splice(cache_list.begin(), cache_list, it->second);
value = it->second->second;
return true;
}
void put(const K& key, const V& value) {
std::lock_guard<std::mutex> lock(mtx);
auto it = cache_map.find(key);
if (it != cache_map.end()) {
// 更新值并移至头部
it->second->second = value;
cache_list.splice(cache_list.begin(), cache_list, it->second);
} else {
// 插入新元素
cache_list.emplace_front(key, value);
cache_map[key] = cache_list.begin();
// 超出容量时淘汰尾部
if (cache_map.size() > capacity) {
auto last = cache_list.back();
cache_map.erase(last.first);
cache_list.pop_back();
}
}
}
};上述实现适用于大多数并发读写场景。若读多写少,可考虑升级为std::shared_mutex(C++17),允许多个读线程同时访问,写操作仍独占锁。
基本上就这些。核心是理解LRU逻辑,再通过互斥锁保护共享状态,即可构建一个实用的线程安全缓存。
以上就是c++++怎么实现一个线程安全的LRU缓存_C++并发编程中的缓存设计与实现的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号