贴个之前用coze写的代码的例子(gpt4),各位可以试试找找它的bug在哪里(人工搞不定的话,可以喂给AI找bug试试)
我下的提示指令是两句话:
1、可否实现一个C++模板类,该类实现LRU缓存的功能,能指定最大缓存的消息个数,以及需要淘汰的时间间隔TTL。
2、请给这个类加上读写锁。
#include <unordered_map>
#include <chrono>
#include <utility>
#include <shared_mutex>
template<typename Key, typename Value>
class LRUCache {
public:
LRUCache(size_t max_size, long long ttl) : _max_size(max_size), _ttl(ttl) {}
void put(const Key& key, const Value& value) {
std::unique_lock<std::shared_timed_mutex> lock(_mutex);
auto now = std::chrono::system_clock::now();
auto item = _cache.find(key);
if (item != _cache.end()) {
_lru_list.erase(item->second.second);
_cache.erase(item);
}
_lru_list.push_front(key);
_cache[key] = {std::make_pair(value, now), _lru_list.begin()};
if (_cache.size() > _max_size) {
auto last = _lru_list.end();
last--;
_cache.erase(*last);
_lru_list.pop_back();
}
remove_expired(now);
}
std::pair<bool, Value> get(const Key& key) {
std::shared_lock<std::shared_timed_mutex> lock(_mutex);
auto item = _cache.find(key);
if (item == _cache.end()) {
return std::make_pair(false, Value());
}
auto now = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - item->second.first.second).count();
if (duration > _ttl) {
lock.unlock(); // Need to unlock here since remove_expired() requires unique_lock
std::unique_lock<std::shared_timed_mutex> ulock(_mutex);
_lru_list.erase(item->second.second);
_cache.erase(item);
return std::make_pair(false, Value());
}
// To modify the list, we need to upgrade to unique lock
lock.unlock();
std::unique_lock<std::shared_timed_mutex> ulock(_mutex);
_lru_list.erase(item->second.second);
_lru_list.push_front(key);
item->second.second = _lru_list.begin();
return std::make_pair(true, item->second.first.first);
}
private:
size_t _max_size;
long long _ttl; // seconds
std::list<Key> _lru_list;
std::unordered_map<Key, std::pair<std::pair<Value, std::chrono::time_point<std::chrono::system_clock>>, typename std::list<Key>::iterator>> _cache;
mutable std::shared_timed_mutex _mutex;
void remove_expired(const std::chrono::time_point<std::chrono::system_clock>& now) {
for (auto it = _lru_list.rbegin(); it != _lru_list.rend();) {
auto cache_it = _cache.find(*it);
if (cache_it != _cache.end()) {
auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - cache_it->second.first.second).count();
if (duration > _ttl) {
_cache.erase(cache_it);
it = std::list<Key>::reverse_iterator(_lru_list.erase(std::next(it).base()));
} else {
++it;
}
} else {
++it;
}
}
}
};
【 在 misskiss 的大作中提到: 】
: 试试4o,不一样的感受。
:
: #发自zSMTH@BKL-AL20
--
FROM 221.218.161.*