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?
views:
112answers:
3
+1
A:
Yes. No memory changes or caching are going to happen under the hood.
sergiom
2010-01-27 17:47:50
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
2010-01-27 17:51:35
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
2010-01-27 17:52:13
@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
2010-01-27 17:53:31
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
2010-01-27 17:54:44
@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
2010-01-27 17:56:32
@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
2010-01-27 18:37:12
+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
2010-01-27 17:55:25
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
2010-01-27 18:38:12