tags:

views:

112

answers:

3

In C++, is it safe to use an std::map or std::vector concurrently in different threads if you are NOT inserting, just doing .find() operations on it?

+1  A: 

Yes. No memory changes or caching are going to happen under the hood.

sergiom
You're making an assumption that the find method is not stateful on all implementations of the standard. It's best not to make assumptions when it comes to C++.
JaredPar
+4  A: 

This is implementation specific and not guaranteed by the standard.

RC
Which implementation would this not work in?
Jay
I think sergiom is probably right in practice, but as I could find no guarantees, I suspect that it's not something we can count on.
Steven Sudit
@Jay: In principle, a container could put off certain cleanup tasks until a later access. Just because the container is accessed as logically const doesn't guarantee that it won't flip some bits (in a thread-unsafe manner) under the hood.
Steven Sudit
I think in MOST cases, you should be okay, but it is not guaranteed by the standard as it mentions nothing about threads and thus does not guarantee thread safety. Due to that fact, it can't be stated that it's safe.
RC
@Jay A more useful question is Which implementations will this work on. The default assumption about something that is not guaranteed by the standard should be that it will not work. Then it is up to the programmer to show that it will work on their particular OS and compiler version.
KeithB
@KeithB: I don't think the lack of standards is a terribly useful argument. There are many things not in the standards that are perfectly reasonable to assume. I think you probably want to look for a positive assertion that this behaviour is not thread safe instead of no assertion implies it's not safe.
Jay
+5  A: 

The current C++ Standard has nothing to say on the subject of threading, and so does not address this issue. The documentation for your specific C++ Standard Library implementation should cover it, however.

anon
From VC++ (Visual Studio 2008), referring to the std containers: 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.
Permaquid