From 9bd937325fb0c61ac3b8714375a0fa827ed4c409 Mon Sep 17 00:00:00 2001 From: greg Date: Sun, 19 Dec 2021 10:58:38 -0500 Subject: [PATCH] Add lazy_emplace_l example. --- examples/lazy_emplace_l.cc | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 examples/lazy_emplace_l.cc diff --git a/examples/lazy_emplace_l.cc b/examples/lazy_emplace_l.cc new file mode 100644 index 0000000..2397855 --- /dev/null +++ b/examples/lazy_emplace_l.cc @@ -0,0 +1,53 @@ +// ------------------------ +// Windows specific example +// ------------------------ +#include +#include "parallel_hashmap/phmap.h" +#include +#include +#include + +class srwlock { + SRWLOCK _lock; + +public: + srwlock() { InitializeSRWLock(&_lock); } + void lock() { AcquireSRWLockExclusive(&_lock); } + void unlock() { ReleaseSRWLockExclusive(&_lock); } +}; + +using Map = phmap::parallel_flat_hash_map, + phmap::priv::hash_default_eq, + std::allocator>, 8, srwlock>; + +class Dict +{ + Map m_stringsMap; + +public: + int addParallel(std::string&& str, volatile long* curIdx) + { + int newIndex = -1; + m_stringsMap.lazy_emplace_l(std::move(str), + [&](int& v) { newIndex = v; }, // called only when key was already present + [&](const Map::constructor& ctor) // construct value_type in place when key not present + { newIndex = InterlockedIncrement(curIdx); ctor(std::move(str), newIndex); }); + + return newIndex; + } +}; + +int main() +{ + size_t totalSize = 6000000; + std::vector values(totalSize); + Dict dict; + volatile long index = 0; + concurrency::parallel_for(size_t(0), size_t(totalSize), + [&](size_t i) { + std::string s = "ab_uu_" + std::to_string(i % 1000000); + values[i] = dict.addParallel(std::move(s), &index); + }); + + return 0; +}