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<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_.erase(ret.first);
        map_.insert(std::pair<K, V>(key, value));
        return;
    }
    return;
}

bool Find(const K& key, V& value)
{
    bool ret = false;
    std::lock_guard<std::mutex> 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<std::mutex> 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<K, V>(key, newValue));
            ret = true;
        }
    }

    return ret;
}

void Erase(const K& key)
{
    std::lock_guard<std::mutex> lock(mutex_);
    map_.erase(key);
}

insert操作时,map中如果已经存在key,则insert不成功,所以这里提供了EnsureInsert函数,当key存在时先删除再插入,确保插入最终值。

总结
SafeMap在stl map基础上封装互斥锁,以确保对map的操作安全。但map中我们通常会进行遍历操作,在SafeMap中则不提供遍历操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

togolife

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值