如何使函数线程安全
How to make function thread safe
这是我将在 unordererd 映射中插入值并定期查询这些值的代码。
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);
}
我将在两个不同的线程中使用此对象,并且我希望何时通过 AddMap 函数进行插入而不是 GetMap 函数应该等待插入完成。 GetMap 函数也会被并发调用。
我当前的代码是否足以解决这个问题?
足够了。互斥锁保证最多一个线程get同时调用get或set。
但是,如果您想实现并发读取,您的代码可能没有优化。在 C++ 中,unordered_map
是一个容器,它具有这样的线程安全性: https://en.cppreference.com/w/cpp/container#Thread_safety 两个线程可以安全地同时调用 get
因为它是一个常量函数,如果没有线程正在修改容器。
这是我将在 unordererd 映射中插入值并定期查询这些值的代码。
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);
}
我将在两个不同的线程中使用此对象,并且我希望何时通过 AddMap 函数进行插入而不是 GetMap 函数应该等待插入完成。 GetMap 函数也会被并发调用。
我当前的代码是否足以解决这个问题?
足够了。互斥锁保证最多一个线程get同时调用get或set。
但是,如果您想实现并发读取,您的代码可能没有优化。在 C++ 中,unordered_map
是一个容器,它具有这样的线程安全性: https://en.cppreference.com/w/cpp/container#Thread_safety 两个线程可以安全地同时调用 get
因为它是一个常量函数,如果没有线程正在修改容器。