Skip to content

File thread_safe_map.h

File List > bindings > ipc > thread_safe_map.h

Go to the documentation of this file

#pragma once

#include <mutex>
#include <shared_mutex>
#include <unordered_map>

// Class: ThreadSafeMap
//   A thread-safe map implementation using std::mutex
template <typename Key, typename Value>
class ThreadSafeMap {
 public:
  // Function: Insert
  //   Inserts a key-value pair into the map
  //   key - key to insert
  //   value - value to insert
  // Returns:
  //   true if inserted, false if already exists
  bool Insert(const Key& key, const Value& value) {
    std::unique_lock<std::shared_mutex> lock(mutex_);
    auto insert_result = map_.insert({key, value});

    return insert_result.second;
  }

  // Function: Find
  //   Finds a value in the map
  //   key - key to find
  //   value - value to return
  bool Find(const Key& key, Value& value) const {
    std::shared_lock<std::shared_mutex> lock(mutex_);
    auto it = map_.find(key);
    if (it == map_.end()) {
      return false;
    }
    value = it->second;
    return true;
  }

  // Function: Erase
  //   Erases a key from the map
  //   key - key to erase
  void Erase(const Key& key) {
    std::unique_lock<std::shared_mutex> lock(mutex_);
    map_.erase(key);
  }

  // Function: ForEach
  //   Iterates over all key-value pairs in the map
  //   func - function to call for each key-value pair
  template <class TFunc>
  void ForEach(TFunc func) const {
    std::shared_lock<std::shared_mutex> lock(mutex_);
    for (const auto& [key, value] : map_) {
      func(key, value);
    }
  }

 private:
  std::unordered_map<Key, Value> map_;
  mutable std::shared_mutex mutex_;
};