简体   繁体   English

如何使 function 线程安全

[英]How to make function thread safe

This is the code where i would be inserting values in a unordererd map and would also query those values at regular intervals.这是我将在无序 map 中插入值的代码,并且还会定期查询这些值。

class MemoryMap
{
private:
    std::unordered_map<std::string, std::string> maps_;
    std::mutex mutex_;
    


public:
    void AddMap(std::string key, std::string value);
    std::string GetMap(std::string key);
    void PrintMemoryMap(std::string key);

};



void MemoryMap::AddMap(std::string key, std::string value)
{
    std::unique_lock<std::mutex> lock(mutex_);
    maps_[key] = value;
    
}

std::string MemoryMap::GetMap(std::string key)
{
    std::unique_lock<std::mutex> lock(mutex_);
    if (maps_.find(key) == maps_.end())
        return "";
    
        return maps_.at(key);
}

I would be using this object in two different threads and i want when insertion would be happening through AddMap function than GetMap function should wait for the insertion to finish.我将在两个不同的线程中使用这个 object,我希望通过 AddMap function 进行插入,而不是 GetMap function 应该等待插入完成。 Also GetMap function would be called concurrently.还将同时调用 GetMap function。

Is my current code sufficient to address this issue?我当前的代码是否足以解决此问题?

It is sufficient.就足够了。 The mutex lock guarantees at most one thread get call get or set at the same time.互斥锁保证最多一个线程同时get 或set 调用。

However, your code might be not optimized if you want to achieve concurrent reads.但是,如果您想实现并发读取,您的代码可能没有经过优化。 In C++, unordered_map is a container, which has thread safety like this: https://en.cppreference.com/w/cpp/container#Thread_safety Two threads can safely call get at the same time because it is a constant function, if no thread is modifying the container. In C++, unordered_map is a container, which has thread safety like this: https://en.cppreference.com/w/cpp/container#Thread_safety Two threads can safely call get at the same time because it is a constant function, if没有线程正在修改容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM