Re: mutexes and const_iterators
On 15 mar, 14:20, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
I am using a map which holds a list of client connections (to a server).=
When a client connects a client gets added to the map and also when a
In various parts of the code the map gets updated - the key is an int an=
the value is a class.
As the map may be accessed by multiple threads I use a mutex to control
access - ie locking whenever an item is added or removed.
I have these questions:
1. Do I also need to lock if I just update and item? I access the item
via an iterator.
2. Do I need to lock if I simply access the map via a const_iterator?
The standard does not (yet) discuss any multi-threading
issues. Therefore, you have to have a look at the thread
safety guarantees that your STL implementation offers. Chances
are that if there is a thread that modifies the map, all
access (including read-only access through iterators) has to
be locked; if _all_ threads operate read-only on the map, you
might not need to lock. However, to be sure you have to check
the documentation of your standard library implementation.
Those are the guarantees for all of the implementations I'm
aware of, and is doubtlessly the guarantee which will be adopted
by the final standard. IMHO, it still leaves open something
like the following:
std::string const* ps = NULL ;
std::mutex::scoped_lock l( mapMutex ) ;
ps = map.find( index )->second ; // Imagine error checking
std::cout << *ps ;
// or *ps = ...
Are the accesses through ps considered to be accesses to the
map. (I would say yes, but... I can't conceive of an
implementation where the std::map code would actually access the
non-key string value in any way, unless it was removing the
element from the map.)
James Kanze (GABI Software) email:firstname.lastname@example.org
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34