【问题标题】:C++ STL Concurrent update to values in fixed size map - Is it safe?C ++ STL同时更新固定大小映射中的值-安全吗?
【发布时间】:2018-04-28 18:51:57
【问题描述】:
我有一个 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() 在每个线程中?
【问题讨论】:
标签:
multithreading
c++11
stl
thread-safety
【解决方案1】:
如here 所述,STL 容器几乎都是const 线程安全的,因此调用任何const 限定的成员函数都不会导致数据竞争。由于std::map::operator[] 不是const 限定的,因此无法保证线程安全。
即使您确保不会调用线程不安全函数(即insert、erase),除非您了解std::map 的底层实现,这可能取决于库(GCC、Clang 等),请注意从共享对象上的多个线程调用 std::map::operator[]。
如果您需要类似地图的行为,请考虑使用专门设计为线程安全的容器(例如 Intel 的 TBB concurrent_hash_map)。