Need advice here: which of the STL container's operati开发者_如何学Pythonons are considered read-only? Take vector<int>
as example, would it be safe to say that any operation that does not alter the underlying int data is read-only? I am writing a multi-threaded program, but not too sure if it is thread-safe to pass container by reference/pointer.
Between, will the same rules apply to basic_string as well? Any recommended resource that helps for quickly gaining understanding on internal mechanism of STL container? Thanks.
Methods declared const most likely won’t modify the container, although you can’t be sure.
When using STL containers in a multithreaded application you will need an external synchronization mechanism. The C++ standard library is not thread safe, and any use from multiple threads without synchronization will result in undefined behavior, assuming that one of the threads change the state of the vector object.
The Standard says nothing on the safety of containers, by the way. But a method marked with const
is guaranteed to not modify the container.*
If thread's will be reading and writing to the data at the same time, you'll need to synchronize them.
**Logically modify, that is. Though I don't know any containers off-hand, any mutable members can change in const methods.*
Use pthread read-write locks in multi-threading threading environment while operating on stl containers. They are quite efficient. Reference for pthread read -write locks:
Pthread Read Write Locks - Yolinux
The only thing which is mentioned in standard is
- Multiple readers are thread safe (duhhhhhh)
- Multiple writers to different containers are thread safe(again duhh...but a smaller one :) this means that no implementation can have static members modification of which can compromise thread safety
精彩评论