C++ STL库中相关容器都是线程不安全的,所以在OpenHarmony的utils中提供的基础C++库中提供了线程安全的SafeMap实现。
OpenHarmony开源库中实现了一套C++公共基础库,其中SafeMap的实现在include/safe_map.h
头文件中。
查看SafeMap的成员定义,其包含一个STL的map变量和一个mutex变量,也就是SafeMap在原map基础上封装了锁的处理。
private:
std::mutex mutex_;
std::map<K, V> map_;
具体看map中常见的insert, delete, find, size等操作,也是先加锁后再执行map相关操作。
bool Insert(const K& key, const V& value)
{
std::lock_guard<std::mutex> lock(mutex_);
auto ret = map_.insert(std::pair<K, V>(key, value));
return ret.second;
}
void EnsureInsert(const K& key, const V& value)
{
std::lock_guard<std::mutex> lock(mutex_);
auto ret = map_.insert(std::pair<K, V>(key, value));
// find key and cannot insert
if (!ret.second) {
map_.