简体   繁体   中英

thread-safe alternative for std::map?

I have a parallized loop and write access to a std::map . I would like to different parts of the map at the same time, ie I want to access map[a] and map[b] for a,b different. At I found out that this is not possible, I wonder, however, if there is a good alternative or how to achieve this in a different way!

I could be wrong, but I believe that modifying existing elements to a map is safe as long as you're not touching the same elements (as this does not modify the underlying structure of the map). So if you insert map[a] and map[b] ahead of time, your separate threads should be able to modify those existing elements.

That said, it's probably cleaner and safer just to use normal synchronization techniques such as mutexes to protect access to the map.

It is quite possible to mutate map[a] and map[b] separately, as long as you do not mutate the underling map .

If you wish to mutate an associative container concurrently, check out concurrent_unordered_map from PPL or TBB.

If possible, you could try giving each worker its own copy of the map and then merging the results. This way no locking would be needed at all.

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