Re: std::map multithreaded access, lock needed?
On Jan 10, 5:01 pm, Andre Kostur <nntps...@kostur.net> wrote:
James Kanze <james.ka...@gmail.com> wrote
innews:aa629021-ef92-4c4b-a498-102877a50a9a@k39g2000hsf.googlegroups.com:
On Jan 10, 2:29 am, "Christopher Pisz" <some...@somewhere.net> wrote:
With the recent acceptance of multithreading questions, I assume this
question is on topic. If not, let me know.
Really? I missed where multithreading became on-topic for
comp.lang.c++...
When was it ever off-topic? The topic here is the C++ language.
Multithreading is definitely relevant to the C++ language, and
has been since C++ implementations which support multi-threading
have become widespread. (Obviously, detailed discussion of a
particular threading model is better handled elsewhere, and
detailed discussion of a particular, non-portable API isn't on
topic. But neither were the question here.)
I have a singleton is going to be accessed by any threads.
My singleton class contains a static std::map that will be
read and written to. I am wondering if I need to lock it
when being read from and written to? The sgi docs lead me
to beleive I do... See LoggerWindow::OpenLog below.
You have to check your library's documentation as to what
thread-safety guarantees it has... but the one that seems to
be the most common (among library implementations that are
intended to be run in a MT environment):
- Different instances of a container are independant (no locks required)
- Multiple readers into a single container is safe (no locks required)
- Writing into a single container requires protection to prevent multiple
writers, and potentially other readers (It may not be safe to attempt to
read & write into the container at the same time. Offhand I can think tha=
t
attempting to do a find into a map at the same time as an insertion is
going on might catch the internal implementation of the map in an
inconsistent state.)
Not "It may not be safe", but "It is undefined behavior" (to
attempt to read and write into the container at the same time).
And it isn't only related to what the code might or might not
do; there are memory synchronization issues involved as well.
--
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