Spaces:
Paused
Paused
| template <typename Key, typename Value> | |
| class ConnMap { | |
| public: | |
| static ConnMap& getInstance() { | |
| static ConnMap instance; // 在首次使用时创建 | |
| return instance; | |
| } | |
| ConnMap(ConnMap const&) = delete; | |
| void operator=(ConnMap 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: | |
| ConnMap() = default; | |
| mutable std::shared_timed_mutex mutex_; | |
| std::map<Key, Value> map_; | |
| }; | |