Reputation: 745
I have read that std::map
is not thread safe. So if I am accessing (read/write) the std::map
from different threads, should I simply wrap the relevant code in a critical section?
Note: I am using Visual C++ 2010.
Upvotes: 0
Views: 234
Reputation: 760
Just got a simultaneous write for the same question. Bottom line : use a read/write lock.
Upvotes: 0
Reputation: 36896
Simple answer: yes. But how to do it properly can be tricky. The basic strategy would be to wrap calls to your map
in critical sections, including wrapping the lifetimes of iterators.
But you also need to make sure that your app's assumptions about the map are handled carefully as well. For example if you need to delete many related items from the map, either make sure other threads are tolerant to only some of those items missing, or wrap the whole batch operation in the critsec. This can easily spiral out of control so you end up wrapping huge amounts of code in critical sections, which will end up causing deadlocks and degrading performance. Careful!
Upvotes: 1