以原子方式访问存储在地图中的资源 [英] Atomically accessing resources stored in a map

查看:63
本文介绍了以原子方式访问存储在地图中的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在映射中存储一些 std::shared_ptr 到 C++ 类实例,例如使用整数键的 std::map.但是,我需要这张地图有两个属性:

I want to store some std::shared_ptr to C++ class instances in a map, e.g. a std::map, using an integer key. However, I need this map to have two properties:

  1. 如果键不存在,则返回错误而不是创建新对象.
  2. 如果密钥确实存在,则以原子方式获取 std::shared_ptr 的副本.IE.应该不可能在一个线程中从地图中删除一个对象,同时在另一个线程中从地图中检索它.

如果可能的话,我想避免使用单个互斥锁(甚至多次读取、单次写入)来从映射中获取和删除对象,以避免开销.

I'd like to avoid having a single mutex (even multiple read, single write) for getting and removing objects from the map if possible, to avoid the overhead.

任何图书馆中都存在这样的地图类吗?如果没有,您能建议如何实施吗?

Does such a map class exist in any library? If not, can you suggest how to implement one?

推荐答案

如果集合内的元素有互斥锁,您可以简单地使用无锁数据结构.在 boost 1.53.0 中用 C++ 实现.

If the elements inside the collection have mutexes you can simply use lock-free data structures. There are implemented in C++ in boost 1.53.0.

然而,我建议再次查看互斥锁 - 在许多情况下,它们将提供更好的无锁数据结构性能(尽管并非总是如此)并且更易于管理.只要没有互斥体循环,你应该没问题.

However I would advice to look at mutexes once again - in many cases they will offer better performance the lock-free data structure (although not always) and are much easier to manage. As long as there is no loop of mutexes you should be fine.

从不创建访问开始使用 std::map::find 如果您使用 C++03(返回迭代器)或 std::map::at 如果你使用 C++11(返回引用).

As of access-without-creation use std::map::find if you use C++03 (returns iterator) or std::map::at if you use C++11 (returns reference).

编辑:实际上std::map::at 可能更糟,除非您假设正常情况是该元素存在(即违反仅将异常用于异常状态而不是正常操作的规则).然而,这可能也取决于适用于例外的哲学.

EDIT: Actually std::map::at is possibly worse unless you assume that the normal case is that element is present (i.e. against rule to use exceptions only for exceptional state instead of normal operation). However it probably depends also on philosophy one applies to exceptions.

这篇关于以原子方式访问存储在地图中的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆