Re: mutexes and const_iterators
On 15 mar, 11:21, "Angus" <nos...@gmail.com> 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 client disconnects.
In various parts of the code the map gets updated - the key is
an int and 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.
And what is supposed to happen if another thread removes the
element you're updating, while you're updating it?
2. Do I need to lock if I simply access the map via a const_iterator?
And what is supposed to happen if another thread removes the
element the iterator points to, thus invalidating it?
The answer to your questions is yes and yes. In this case,
there are obvious scenarios in which the code breaks otherwise.
The rule, however, is far more general, and doesn't depend on
such scenarios: if any thread may modify the object, *all*
accesses to the object must be externally synchronized. Period.
There are no exceptions. An iterator into a map accesses (parts
of) the map, and an element in the map is considered part of the
map. (In practice, I think that if you can somehow guarantee
that the element in question is not itself being removed or
modified in any way, you can probably get away with 1, although
I suspect that the final standard will say that even that is
undefined behavior.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
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