Spaces:
Paused
Paused
File size: 1,241 Bytes
2faa101 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
#ifndef PROXYSERVER_CONN_MAP_H
#define PROXYSERVER_CONN_MAP_H
#include <iostream>
#include <map>
#include <shared_mutex>
#include <mutex>
template <typename Key, typename Value>
class TcpClientMap {
public:
static TcpClientMap& getInstance() {
static TcpClientMap instance; // 在首次使用时创建
return instance;
}
TcpClientMap(TcpClientMap const&) = delete;
void operator=(TcpClientMap const&) = delete;
void add(const Key& key, const Value& value) {
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
map_[key] = value;
}
Value* get(const Key& key) const {
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
auto it = map_.find(key);
if (it != map_.end()) {
return (Value*)(&(it->second));
}
return nullptr;
}
void remove(const Key& key) {
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
map_.erase(key);
}
void clear() {
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
map_.clear();
}
private:
TcpClientMap() = default;
mutable std::shared_timed_mutex mutex_;
std::map<Key, Value> map_;
};
#endif //PROXYSERVER_CONN_MAP_H |