I have a global object holding several c++ std::map objects. This object is supposed to be read only in a multithreaded environment. But i'm not sure whether there is any write operation when a C++ std::map object is being read within the implementation of std::map. The IDE is Visual Studio 2008. Should I provide some synchronization mechanisms for read operations?
views:
128answers:
4There is at least one "portable" problem, in that if you're using operator[]
to read, it is not necessarily a read only operation in that if the item doesn't exist yet in the map, it will be created. Beyond that, it becomes a matter of the specific implementation.
Yes this will be OK provided nobody is writing to the map. See here for full details.
http://stackoverflow.com/questions/1846186/thread-safety-of-stdmap-for-read-only-operations
If you use the subscript operator, then no. There's a chance that the subscript operator (map[1]) will alter the map's structure.
However, if you use the find method with const_iterators, it is reasonable safe. Just remember that all those iterators may become invalid if the map is altered.
With that said, it is still probably an unsafe idea.
See here for the specifics of the std library that ships with VC++ 2008:
A single object is thread safe for reading from multiple threads. For example, given an object A, it is safe to read A from thread 1 and from thread 2 simultaneously.
There are no rules regarding the std containers' thread safety, it's up to the library developers. So always check the documentation of your specific std implementation.