我有一个C ++ STL地图
std::map < std::thread_id, int > some_map
,其大小固定为num_threads
,所有位置在开始时初始化为0.
some_map[id1] = 0;
some_map[id2] = 0;
...
问题:如果每个线程将容器修改为
,是否安全 每个帖子中都有 some_map[std::this_thread::get_id()] = rand()
吗?
答案 0 :(得分:1)
如上所述here,STL容器几乎统一const
线程安全,因此调用任何const
- 限定的成员函数不会导致数据争用。由于std::map::operator[]
不是const
- 合格,因此无法保证线程安全。
即使,您确保不会调用线程不安全的函数(即insert
,erase
),除非您了解{{1}的基础实现},它可以依赖于库(GCC,Clang等),要小心从共享对象上的多个线程调用std::map
。
如果您需要类似地图的行为,请考虑使用专门设计为线程安全的容器(例如,英特尔&#TB; std::map::operator[]
)。