问题描述
我正在开发一个需要std::map
的程序,具体来说就是这样的map<string,map<string,int>>
-它的意思是类似于银行兑换率-第一个字符串是原始货币,第二个字符串是所需的一个,整数是它们的速率.整个地图将只读.我还需要互斥锁吗?我对整个线程的安全性有些困惑,因为这是我的第一个更大的多线程程序.
I am working on a program that needs std::map
and specifically one like this map<string,map<string,int>>
- it is meant to be something like bank change rates - the first string is the original currency and the one in the second map is the desired one and the int is their rate. This whole map will be read only. Do I still need mutexes ? I am a bit confused about the whole thread safety, since this is my first bigger multi-threaded program.
推荐答案
如果您在谈论标准std::map
,并且没有线程写入该标准,则不需要同步.并发读取而无写入是可以的.
If you are talking about the standard std::map
and no thread writes to it, no synchronization is required. Concurrent reads without writes are fine.
但是,如果至少有一个线程在映射上执行写操作,则确实需要某种保护,例如互斥锁.
If however at least one thread performs writes on the map, you will indeed need some sort of protection like a mutex.
请注意,std::map::operator[]
视为写入,因此请使用std::map::at
(如果键可能不存在于映射中,则使用std::map::find
).您可以通过仅通过const map&
引用共享映射来使编译器保护您免受意外写入的影响.
Be aware that std::map::operator[]
counts as write, so use std::map::at
(or std::map::find
if the key may not exist in the map) instead. You can make the compiler protect you from accidental writes by only referring to the shared map via const map&
.
已在OP中得到澄清.为了完整起见:请注意,其他类可能具有mutable
成员.对于那些人,甚至通过const&
进行访问也可能会引起比赛.如有疑问,请查阅文档或使用其他工具进行并行编程.
Was clarified to be the case in the OP. For completeness' sake: Note that other classes may have mutable
members. For those, even access through const&
may introduce a race. If in doubt, check the documentation or use something else for parallel programming.
这篇关于C ++线程安全-映射阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!