我有一个std::map,用于将值(字段ID)映射到可读的字符串。在启动任何其他线程之前,该映射只初始化一次,并且此后不再修改。目前,我为每个线程提供其自己的该映射的副本,但这显然浪费了内存并减慢了程序启动速度。因此,我考虑给每个线程一个指向该映射的指针,但这会带来线程安全问题。
如果我只是使用以下代码从该映射中读取:
备注:目前我正在使用Visual Studio 2008,但我希望这适用于大多数主要的STL实现。
更新:编辑了代码示例以解决const正确性问题。
如果我只是使用以下代码从该映射中读取:
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正确性问题。