folly/AtomicHashmap.h

folly/AtomicHashmap.h introduces a synchronized UnorderedAssociativeContainer implementation designed for extreme performance in heavily multithreaded environments (about 2-5x faster than tbb::concurrent_hash_map) and good memory usage properties. Find and iteration are wait-free, insert has key-level lock granularity, there is minimal memory overhead, and permanent 32-bit ids can be used to reference each element.

Limitations


Although it can provide extreme performance, AtomicHashmap has some unique limitations as well.

  • The space for erased elements cannot be reclaimed (they are tombstoned forever) so it's generally not a good idea to use this if you're erasing things a lot.

  • Only supports 32 or 64 bit keys - this is because they must be atomically compare-and-swap'ed.

  • Growth beyond initialization reduces performance - if you don't know the approximate number of elements you'll be inserting into the map, you probably shouldn't use this class.

  • Must manage synchronization externally in order to modify values in the map after insertion. Lock pools are a common way to do this, or you may consider using folly::PackedSyncPtr<T> as your ValueT.

  • Must define special reserved key values for empty, erased, and locked elements.

For a complete list of limitations and departures from the UnorderedAssociativeContainer concept, see folly/AtomicHashMap.h

Unique Features


  • value_type references remain valid as long as the map itself. Note this is not true for most other probing hash maps which will move elements when rehashing, which is necessary for them to grow. AtomicHashMap grows by chaining additional slabs, so elements never need to be moved.

  • Unique 32-bit ids can be used to reference elements in the map via iterator::getIndex(). This can be helpful to save memory in the rest of the application by replacing 64-bit pointers or keys.

  • Iterators are never invalidated. This means you can iterate through the map while simultaneously inserting and erasing. This is particularly useful for non-blocking map serialization.

Usage


Usage is similar to most maps, although note the conspicuous lack of operator[] which encourages non thread-safe access patterns.

Below is a synchronized key counter implementation that allows the counter values to be incremented in parallel with serializing all the values to a string.

   class Counters {
private:
AtomicHashMap<int64_t,int64_t> ahm; public:
explicit Counters(size_t numCounters) : ahm(numCounters) {} void increment(int64_t obj_id) {
auto ret = ahm.insert(make_pair(obj_id, ));
if (!ret.second) {
// obj_id already exists, increment
NoBarrier_AtomicIncrement(&ret.first->second, );
}
} int64_t getValue(int64_t obj_id) {
auto ret = ahm.find(obj_id);
return ret != ahm.end() ? ret->second : ;
} // Serialize the counters without blocking increments
string toString() {
string ret = "{\n";
ret.reserve(ahm.size() * );
for (const auto& e : ahm) {
ret += folly::to<string>(
" [", e.first, ":", NoBarrier_Load(&e.second), "]\n");
}
ret += "}\n";
return ret;
}
};

Implementation


AtomicHashMap is a composition of AtomicHashArray submaps, which implement the meat of the functionality. Only one AHA is created on initialization, and additional submaps are appended if the first one gets full. If the AHM grows, there will be multiple submaps that must be probed in series to find a given key. The more growth, the more submaps will be chained, and the slower it will get. If the initial size estimate is good, only one submap will ever be created and performance will be optimal.

AtomicHashArray is a fixed-size probing hash map (also referred to as an open addressed hash map) where hash collisions are resolved by checking subsequent elements. This means that they can be allocated in slabs as arrays of value_type elements, have excellent cache performance, and have no memory overhead from storing pointers.

The algorithm is simple - when inserting, the key is hash-mod'ed to an offset, and that element-key is atomically compare-and-swap'ed with the locked key value. If successful, the value is written and the element-key is unlocked by setting it to the input key value. If the compare fails, the next element is tried until success or the map is full.

Finds are even simpler. The key is hash-mod'ed to an offset, and the element-key is examined. If it is the same as the input key, the reference is returned, if it's the empty key, failure is returned, otherwise the next key is tried. This can be done wait-free without any atomic instructions because the elements are always in a valid state.

Erase is done by finding the key, then compare-and-swap'ing the element-key with the reserved erased key value. If the swap succeeds, return success, otherwise return failure (the element was erased by a competing thread). If the key does not exist, return failure.

AtomicHashMap的更多相关文章

  1. folly::AtomicHashmap源码分析(二)

    本文为原创,转载请注明:http://www.cnblogs.com/gistao/ 背景 上一篇只是细致的把源码分析了一遍,而源码背后的设计思想并没有写,设计思想往往是最重要的,没有它,基本无法做整 ...

  2. folly::AtomicHashmap源码分析(一)

    本文为原创,转载请注明:http://www.cnblogs.com/gistao/ Atomic的两点背景 看下这个场景,老张去厕所,发现门是锁着的,他就在门口等着里边人出来,此时小王也来了,他想了 ...

  3. folly学习心得(转)

    原文地址:  https://www.cnblogs.com/Leo_wl/archive/2012/06/27/2566346.html   阅读目录 学习代码库的一般步骤 folly库的学习心得 ...

  4. Folly: Facebook Open-source Library Readme.md 和 Overview.md(感觉包含的东西并不多,还是Boost更有用)

    folly/ For a high level overview see the README Components Below is a list of (some) Folly component ...

  5. 《HelloGitHub》第 75 期

    兴趣是最好的老师,HelloGitHub 让你对编程感兴趣! 简介 HelloGitHub 分享 GitHub 上有趣.入门级的开源项目. https://github.com/521xueweiha ...

随机推荐

  1. 如何利用$_SERVER["PHP_SELF"]变量植入script代码?

    假如我们是黑客,可以诱骗用户访问如下链接, 相当于用户会在浏览器地址栏中输入以下地址: http://www.xxx.com/test_form.php/%22%3E%3Cscript%3Ealert ...

  2. encodeURI()和encodeURIcomponent()的共同点和不同点

    共同点: 1.encodeURI和encodeURIcomponent都是Global对象, Global对象在某种意义上是违一个终极的兜底对象,换句话说,不属于任何其他对象的属性和方法,最终都是她的 ...

  3. 每周荐书:云原生、Docker、Web算法(评论送书)

    每周荐书:云原生.Docker.Web算法(评论送书) 感谢大家对每周荐书栏目的支持,先公布下上周中奖名单 名优秀评论可以免费获得此书.   云原生应用架构实践 云原生架构,关注简化开发流程.提升研发 ...

  4. Graham扫描法

    Graham扫描法求凸包的模板 运行之后可以得到存有凸包顶点的栈s和栈顶指针top,n代表总点数 这个模板我当时调了很久,主要难点有两个,一个是正确的极角排序,一个是出栈入栈的细节操作,逆时针扫描,这 ...

  5. CMake入门实践

    为了更好的代码管理,选择一款make工具非常重要,cmake取百家之长,现在在github上已经是工程管理的常客了,最大的优势是跨平台.本文将避开理论,直接教你如何在windows和linux上实现c ...

  6. 6LowPan 开发之开山篇

    本文参考: http://blog.csdn.net/xukai871105/article/details/9204101   1.基本概念   1) instant contikit    Ubu ...

  7. Python:版本升级(Mac OS X)

    Mac OS X 10.8及以后的版本都预装了Python 2.7,但是在Mac上(Unix-like OS)上修改Python的版本并不如Windows方便.这篇文章的目标是要将Mac自带的Pyth ...

  8. 跳转后全屏,兼容大部分浏览器JavaScript

    <!DOCTYPE html> <html> <head> <title>测试</title> </head> <body ...

  9. ubuntu 下jdk安装配置

    下载jdk-8u71-linux-x64.tar.gz 创建jvm文件夹(/usr/lib/jvm) sudo mkdir /usr/lib/jvm 创建jvm文件夹(/usr/lib/jvm) su ...

  10. HihoCoder 1044 垃圾清理 (优化:状态压缩)

    状态压缩·一 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和小Ho在兑换到了喜欢的奖品之后,便继续起了他们的美国之行,思来想去,他们决定乘坐火车前往下一座城市— ...