std::在单独的线程中插入时读取地图
std::map reading while inserting in a separate thread
我有这样的地图
map<string,A>
现在,当我从线程 I 遍历映射时,线程 II 正在向其插入一些内容。 这种插入会影响读数吗?
是的,插入会影响读数。该标准不提供线程安全保证。存在竞争条件,它会导致未定义的行为。
是的,它会影响阅读。您需要在这两个线程之间建立额外的同步机制。阅读有关std::mutex
和std::unique_lock
的信息。
请参阅下面的示例代码:
#include <map>
#include <string>
#include <mutex>
#include <memory>
class MapWithMutex
{
public:
int readFromMap(const std::string& key)
{
std::unique_lock<std::mutex>(mtx);
//add some check if elements exists
return myMap[key];
}
void insertToMap(const std::string& key, int value)
{
//add check if element doesn't already exist
std::unique_lock<std::mutex>(mtx);
myMap[key] = value;
}
private:
std::map<std::string,int> myMap;
std::mutex mtx;
};
int main() {
MapWithMutex thSafeMap;
//pass thSafeMap object to threads
return 0;
}
记住使关键部分尽可能小
相关文章:
- 将一对插入地图并增加计数?
- 当我将其插入无序地图时,矢量的容量为 0
- 为什么不插入地图?
- 为什么emplace_hint比插入地图慢?
- 无法将智能指针插入地图
- 如何将元组插入地图?
- 在C++中访问和插入地图的地图(嵌套地图)
- 通过EMPLEPE()将对象指针插入地图中
- 将mpfr_t对象插入地图中的值
- 有效地将值插入地图.更好地增加或减少键
- C :将向量插入地图
- C - 插入地图或向量时的分割故障
- 当我尝试将一对插入地图时,Qt程序seg出错
- C++ 将字符串插入地图时出现编译错误
- 将unique_ptr插入地图,指针被销毁
- 为什么我在插入地图时遇到 seg 错误
- 插入地图时出现分割错误
- 当我插入地图时,会出现Valgrind错误
- 将项目插入地图,其中还有 2 张地图
- 如何将数据插入地图<字符串,设置<string>> C++?