std::unordered_map 是 C++ 标准库中的哈希表实现的关联数组,它本身不是线程安全的,多个线程同时访问和修改同一个 unordered_map 可能会导致数据竞争和未定义行为。
使用 C++11 标准库中的 std::shared_mutex 实现读写锁来保护 std::unordered_map,允许多个线程同时读取 unordered_map,但只允许一个线程写入 unordered_map,可以提高并发性能。
#include <unordered_map>
#include <shared_mutex>
#include <iostream>
#include <mutex>
#include <map>
#include <functional>
template<typename Key, typename Value>
class safeUnorderedMap {
public:
safeUnorderedMap() {}
void insert(const Key& key, const Value& value) {
std::unique_lock<std::shared_mutex> lock(mutex_);
map_[key] = value;
}
void erase(const Key& key) {
std::unique_lock<std::shared_mutex> lock(mutex_);
map_.erase(key);
}
bool find(const Key& key, Value& value) const {
std::shared_lock<std::shared_mutex> lock(mutex_);
auto it = map_.find(key);
if (it == map_.end()) {
return false;
}
value = it->second;
return true;
}
void clear() {
std::unique_lock<std::shared_mutex> lock(mutex_);
map_.clear();
}
size_t size() const {
std::lock_guard<std::shared_mutex> lock(mutex_);
return map_.size();
}
std::map<Key, Value> getMap() const {
std::lock_guard<std::shared_mutex> lock(mutex_);
return map_;
}
void forEach(std::function<void(const Key&, const Value&)> f) const {
std::shared_lock<std::shared_mutex> lock(mutex_);
for (const auto& kv : map_) {
f(kv.first, kv.second);
}
}
private:
mutable std::shared_mutex mutex_;
std::unordered_map<Key, Value> map_;
};
template<typename Key, typename Value>
class safeMap : public safeUnorderedMap<Key, Value>
{
private:
mutable std::shared_mutex mutex_;
std::map<Key, Value> map_;
};
int main()
{
safeMap<int, int> myMap;
// 插入元素
myMap.insert(1, 10);
myMap.insert(2, 20);
myMap.insert(3, 30);
// 查找元素
int value;
if (myMap.find(2, value)) {
std::cout << "value of key 2: " << value << std::endl;
} else {
std::cout << "key 2 not found" << std::endl;
}
// 删除元素
myMap.erase(3);
// 清空容器
myMap.clear();
// 遍历容器
myMap.insert(4, 40);
myMap.insert(5, 50);
myMap.forEach([](const int& key, const int& value) {
std::cout << key << ": " << value << std::endl;
});
return 0;
}