Is it necessary to lock around STL containers in order to read their data?
I am writing a multi-threaded server, which contains开发者_运维技巧 5 or 6 global data structures (maps, vectors, etc.) and am trying to figure out if I need to hold mutexes for certain data in order to read values from maps or vectors, or if it is only necessary to hold a mutex when I am going to alter the data/add new items.
You need to synchronize access to the container if multiple threads are accessing the container and at least one of those threads is modifying the contents of the container. If none of the threads ever modify the contents of the container, you do not need to synchronize access to it.
[Note that the C++ Language Standard does not mention threads (at least not yet), so it isn't required that containers are usable from multiple threads at all. That said, what I've said above is true for at least all of the major implementations of the Standard Library and is the requirement in the forthcoming C++0x revision to the C++ Language Standard.]
精彩评论