c++ - 只读操作的 std::map 线程安全

标签 c++ multithreading stl thread-safety stdmap

我有一个 std::map 用于将值(字段 ID)映射到人类可读的字符串。当我的程序在任何其他线程启动之前启动时,这个映射被初始化一次,之后它就再也不会被修改了。现在,我给每个线程自己的这个(相当大的)映射拷贝,但这显然是对内存的低效使用,并且会减慢程序启动速度。所以我想给每个线程一个指向映射的指针,但这会引发线程安全问题。

如果我所做的只是使用以下代码从 map 中读取:

std::string name;
//here N is the field id for which I want the human readable name
unsigned field_id = N; 
std::map<unsigned,std::string>::const_iterator map_it;

// fields_p is a const std::map<unsigned, std::string>* to the map concerned.
// multiple threads will share this.
map_it = fields_p->find(field_id);
if (map_it != fields_p->end())
{
    name = map_it->second;
}
else
{
    name = "";
}

这是否可行,或者从多个线程读取 std::map 是否存在问题?

注意:我目前正在使用 Visual Studio 2008,但我希望它能够在大多数主要的 STL 实现中工作。

更新:修改了 const 正确性的代码示例。

最佳答案

只要您的 map 保持不变,这将适用于多个线程。您使用的 map 实际上是不可变的,因此任何查找实际上都会在不会更改的 map 中进行查找。

这是一个相关链接:http://www.sgi.com/tech/stl/thread_safety.html

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.

您属于“对共享容器的同时读取访问”类别。

注意:这适用于 SGI 实现。您需要检查是否使用其他实现。据我所知,在似乎被广泛用作替代方案的两种实现中,STLPort 具有内置的线程安全性。不过我不知道 Apache 的实现。

关于c++ - 只读操作的 std::map 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1846186/

相关文章:

c++ - 如何在 Linux/OS X 上打印 wstring?

php - 负载平衡 PHP 内置服务器?

c# - Windows 窗体线程正在失去他们的文化

java - Android java.lang.IllegalStateException,不在主线程

c++ - 处理类和类的模板函数*

c# - 关于如何提取 Pandora 点赞并将它们放入电子表格的任何提示? (C++/C#)

c++ - 如何更新std::set的现有元素?

c++ - 您使用什么调试器工具来查看 STL 容器的内容(在 Linux 上)

c++ - 具有自定义比较器的最小优先级队列

c++ - C++ 中的 Functor 永远不能抽象吗?