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.
Yes it is. Show activity on this post.
It isn't thread safe, insert from two threads and you can end up in an inconstant state.
Thread safety becomes a concern if there is at least a single entry point which can be accessed by multiple threads. If a piece of code is accessed by multiple threads and is calling other method/class/etc., then all this code tree becomes vulnerable.
To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.
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.
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&
.
†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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With