开发者

Can I get count from a hash_map while adding some items to it?

开发者 https://www.devze.com 2023-03-15 17:22 出处:网络
For both windows and linux: In multi-threaded application, in case I do开发者_如何学编程 not care the very exactly when getting the count of a hash_map, then can I safely call {hash_map}.size() while

For both windows and linux:

In multi-threaded application, in case I do开发者_如何学编程 not care the very exactly when getting the count of a hash_map, then can I safely call {hash_map}.size() while still allow other threads to add/delete items on that {hash_map}?

Thank you.


No

The STL containers (if that's what you're using) are not thread-safe.

size() is likely to walk the buckets and count the numbers. Modifying that data structure while another thread walks it is dangerous (that is, dangerous like a drunk elephant in a minefield).

I'd recommend wrapping your hash_map with some functions that update the count separately, as an atomic integer. That value will not be exact, but probably will be close enough, and it will reduce thread contention between size() and insert/erase operations.


This strongly depends on the type of your hash_map. If it's std::unordered_map, then the answer is NO --- concurrent calls to member functions from separate threads are not permitted if any of those is a non-const member function.

If, on the other hand, you are using a type designed for concurrent access, then the answer may very well be yes.

0

精彩评论

暂无评论...
验证码 换一张
取 消