gpt4 book ai didi

c++ - 来自并发 HashMap 的迭代器是否安全?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:23:18 25 4
gpt4 key购买 nike

我目前正在使用 Facebook's concurrent hash map我想知道这样的事情是否可能:

folly::ConcurrentHashMap<std::string, some_class> m;

// add some elements

const auto it = m.find("a");

// during this time, another thread removes the "a" element

if (it != m.end())
it->second.something(); // it is now an invalid iterator

在阅读了 HashMap 的源代码后,我发现了这个:

Iterators hold hazard pointers to the returned elements. Elements can only be accessed while Iterators are still valid!

这非常令人不安,感觉使用任何返回的迭代器都是不安全的,是这样吗?

最佳答案

返回的迭代器可以安全使用;但是,迭代器对象必须处于事件状态才能安全访问解除引用的值。

“危险指针”使引用的值保持事件状态,直到迭代器被破坏。

operator[]at() 返回给定键的实际值,因此不能返回包含危险指针的代理对象。为了确保它们永远不会返回对死对象的引用,它们会返回值的拷贝。

无论您使用迭代器,还是 operator[]/at(),您都将在访问数据时对键的值进行操作,而不是给定键的最新值。

关于c++ - 来自并发 HashMap 的迭代器是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49430314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com