C++ 线程安全 Map 是指在多线程环境下,能够保证对 Map 数据结构的并发访问是安全的,不会出现数据竞争和不一致的问题。线程安全 Map 通常通过内部同步机制来实现,如互斥锁(mutex)、读写锁(read-write lock)等。
std::map
本身不是线程安全的,但可以通过外部同步机制(如互斥锁)来实现线程安全。std::shared_mutex
可以用于实现读写锁。boost::shared_mutex
和 boost::shared_lock
提供了读写锁的实现。tbb::concurrent_hash_map
是 Intel Threading Building Blocks 提供的线程安全哈希表。以下是一个使用 std::map
和 std::shared_mutex
实现线程安全 Map 的示例:
#include <iostream>
#include <map>
#include <shared_mutex>
#include <thread>
template <typename Key, typename Value>
class ThreadSafeMap {
public:
void insert(const Key& key, const Value& value) {
std::unique_lock<std::shared_mutex> lock(mutex_);
map_[key] = value;
}
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()) {
value = it->second;
return true;
}
return false;
}
private:
mutable std::shared_mutex mutex_;
std::map<Key, Value> map_;
};
void writer(ThreadSafeMap<int, std::string>& map, int key, const std::string& value) {
map.insert(key, value);
}
void reader(const ThreadSafeMap<int, std::string>& map, int key) {
std::string value;
if (map.find(key, value)) {
std::cout << "Key " << key << " has value " << value << std::endl;
} else {
std::cout << "Key " << key << " not found" << std::endl;
}
}
int main() {
ThreadSafeMap<int, std::string> map;
std::thread t1(writer, std::ref(map), 1, "one");
std::thread t2(reader, std::ref(map), 1);
std::thread t3(writer, std::ref(map), 2, "two");
std::thread t4(reader, std::ref(map), 2);
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
问题:在多线程环境下,对 Map 进行并发读写时可能会出现数据竞争和不一致的问题。
原因:多个线程同时读写同一个 Map,没有进行适当的同步控制。
解决方法:
tbb::concurrent_hash_map
。通过上述方法,可以有效解决多线程环境下 Map 的线程安全问题。
领取专属 10元无门槛券
手把手带您无忧上云