简体   繁体   English

从不同的线程访问std :: map

[英]Access std::map from different threads

I have read that std::map is not thread safe. 我读过std::map不是线程安全的。 So if I am accessing (read/write) the std::map from different threads, should I simply wrap the relevant code in a critical section? 因此,如果我要从其他线程访问(读/写) std::map ,是否应该将相关代码包装在关键部分?

Note: I am using Visual C++ 2010. 注意:我正在使用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. 基本策略是将对map调用包装在关键部分,包括包装迭代器的生命周期。

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. 例如,如果您需要从地图中删除许多相关项,请确保其他线程仅容忍那些丢失的某些项,或者将整个批处理操作包装在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. 底线:使用读/写锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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