简体   繁体   中英

Access std::map from different threads

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.

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!

Just got a simultaneous write for the same question. Bottom line : use a read/write lock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM