Xirema

Concurrent Map.h

Feb 17th, 2016
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #pragma once
  2. #include<map>
  3. #include<condition_variable>
  4. #include<mutex>
  5. #include<set>
  6. namespace concurrent {
  7.  
  8.     template<typename K, typename V>
  9.     class map {
  10.     private:
  11.         typedef std::unique_lock<std::mutex> guard;
  12.         typedef std::map<K, V> map_type;
  13.         typedef std::pair<K, V> entry_type;
  14.         map_type _map;
  15.         mutable std::mutex mutex;
  16.         std::condition_variable cond;
  17.     public:
  18.         void insert(const entry_type & e) {
  19.             guard lock(mutex);
  20.             _map.insert(e);
  21.         }
  22.  
  23.         V & operator[](const K & key) {
  24.             guard lock(mutex);
  25.             return _map[key];
  26.         }
  27.  
  28.         const V & at(const K & key) const {
  29.             guard lock(mutex);
  30.             return _map.at(key);
  31.         }
  32.  
  33.         bool contains(const K & key) const {
  34.             guard lock(mutex);
  35.             return _map.find(key) != _map.end();
  36.         }
  37.  
  38.         bool empty() const {
  39.             guard lock(mutex);
  40.             return _map.empty();
  41.         }
  42.  
  43.         size_t erase(const K & key) {
  44.             guard lock(mutex);
  45.             return _map.erase(key);
  46.         }
  47.  
  48.         std::set<K> getKeySet() const {
  49.             guard lock(mutex);
  50.             std::set<K> keys;
  51.             for (const auto & pair : _map) {
  52.                 keys.insert(pair.first);
  53.             }
  54.             return keys;
  55.         }
  56.     };
  57. }
Add Comment
Please, Sign In to add comment