Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ thread safety - map reading

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.

like image 599
Jesse_Pinkman Avatar asked Mar 12 '16 15:03

Jesse_Pinkman


People also ask

Is reading from MAP thread safe?

Yes it is. Show activity on this post.

Is map thread safe in C++?

It isn't thread safe, insert from two threads and you can end up in an inconstant state.

When should I worry about thread safety?

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.

How do you know if thread safe?

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.


1 Answers

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.

like image 52
Baum mit Augen Avatar answered Oct 02 '22 22:10

Baum mit Augen