c++ - 在读取地图成员时调用 unordered_map::operator[] 是否安全?
问题描述
我知道我可能无法同时从多个线程访问operator[]
。std::unordered_map
但是,假设我用互斥锁包围operator[]
调用本身,而访问元素本身仍然是并发的:
我是否允许通过指针读取/写入地图的元素,同时另一个线程正在调用operator[]
?
例如:
// This code will run concurrently from multiple threads
Thing* thing = nullptr;
{
std::lock_guard<std::mutex> lock(my_mutex);
thing = &my_map[thread_id];
}
// This may happen at the same time operator[] is called
thing->value += 10;
这安全吗?
或者,例如:可能operator[]
会在内存中移动东西,从而使当前Thing*
由不同线程持有的指针无效?
解决方案
推荐阅读
- java - Selenide - 为每个 Junit 5 测试创建新驱动程序
- command-line-interface - NativeScript CLI 基础知识:设置后没有 main-page.xml 或 app.css 文件
- javascript - 将列表 Ajax(Json) 传递给 Controller C# MVC
- api - 如何确定 API 调用期间调用的所有函数的执行时间?
- amazon-web-services - Alexa 部署到 us-west-2?
- terminal - 如何以及是否在没有 Ncurses 的情况下为文本着色
- matlab - 如何在MATLAB中的图形的ylabel上写一个方程?
- php - 在进行注册之前检查用户是否登录
- asp.net-core-2.1 - 如何在 .net core 2 项目中启用 cors 在 apache2 服务器中运行
- sql - 列的 Netezza 时间戳数据类型