在向 hash_map 添加一些项目时,我可以从 hash_map 中获取计数吗?

发布于 2024-11-17 09:41:12 字数 136 浏览 3 评论 0原文

对于Windows和Linux:

在多线程应用程序中,如果我在获取hash_map的计数时不太关心,那么我可以安全地调用{hash_map}.size(),同时仍然允许其他线程添加/删除{hash_map} 上的项目?

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长安忆 2024-11-24 09:41:12

STL 容器(如果您正在使用该容器)不是线程安全的。

size() 可能会遍历桶并计算数字。在另一个线程遍历该数据结构时修改该数据结构是危险的(也就是说,就像雷区中喝醉的大象一样危险)。

我建议使用一些单独更新计数的函数来包装您的 hash_map 作为原子整数。该值并不准确,但可能足够接近,并且它将减少 size() 和插入/擦除操作之间的线程争用。

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.

蓝天 2024-11-24 09:41:12

这很大程度上取决于 hash_map 的类型。如果是 std::unordered_map,那么答案是NO --- 如果其中任何一个是非,则不允许从单独的线程并发调用成员函数>const 成员函数。

另一方面,如果您使用的是专为并发访问而设计的类型,那么答案很可能是肯定的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文