OpenHarmony多线程安全map实现解析
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 map_;
具体看map中常见的insert, delete, find, size等操作,也是先加锁后再执行map相关操作。
bool Insert(const K& key, const V& value){ std::lock_guard lock(mutex_); auto ret = map_.insert(std::pair(key, value)); return ret.second;}void EnsureInsert(const K& key, const V& value){ std::lock_guard lock(mutex_); auto ret = map_.insert(std::pair(key, value)); // find key and cannot insert if (!ret.second) { map_.erase(ret.first); map_.insert(std::pair(key, value)); return; } return;}bool Find(const K& key, V& value){ bool ret = false; std::lock_guard lock(mutex_); auto iter = map_.find(key); if (iter != map_.end()) { value = iter->second; ret = true; } return ret;}bool FindOldAndSetNew(const K& key, V& oldValue, const V& newValue){ bool ret = false; std::lock_guard lock(mutex_); if (map_.size() > 0) { auto iter = map_.find(key); if (iter != map_.end()) { oldValue = iter->second; map_.erase(iter); map_.insert(std::pair(key, newValue)); ret = true; } } return ret;}void Erase(const K& key){ std::lock_guard lock(mutex_); map_.erase(key);}
insert操作时,map中如果已经存在key,则insert不成功,所以这里提供了EnsureInsert
函数,当key存在时先删除再插入,确保插入最终值。
总结:
SafeMap在stl map基础上封装互斥锁,以确保对map的操作安全。但map中我们通常会进行遍历操作,在SafeMap中则不提供遍历操作。