Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <typename Key, typename Value>
- class ConcurrentMap {
- public:
- static_assert(std::is_integral_v<Key>, "ConcurrentMap supports only integer keys"s);
- struct Access {
- Access(Value& valueToRef, std::mutex& mtx )
- : ref_to_value(valueToRef), mutex_(mtx) {
- mutex_.lock();
- }
- ~Access() {
- mutex_.unlock();
- }
- Value& ref_to_value;
- std::mutex& mutex_;
- };
- explicit ConcurrentMap(size_t bucket_count)
- : maps_(bucket_count),
- bucketCount_(bucket_count),
- mutexes_(bucket_count) {}
- Access operator[](const Key& key)
- {
- auto mapId = static_cast<uint64_t>(key) % bucketCount_;
- return Access(maps_[mapId][key], mutexes_[mapId]);
- }
- std::map<Key, Value> BuildOrdinaryMap()
- {
- std::map<Key, Value> result;
- for (std::size_t idx = 0; idx < maps_.size(); ++idx) {
- std::lock_guard<std::mutex> guard(mutexes_[idx]);
- for (auto const & [k, v] : maps_[idx]) {
- result[k] = v;
- }
- }
- return result;
- }
- private:
- std::vector<std::map<Key,Value>> maps_;
- size_t bucketCount_;
- std::vector<std::mutex> mutexes_;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement