ThreadSafeDenseMap.h revision 360784
1//===-- ThreadSafeDenseMap.h ------------------------------------------*- C++
2//-*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef liblldb_ThreadSafeDenseMap_h_
11#define liblldb_ThreadSafeDenseMap_h_
12
13#include <mutex>
14
15#include "llvm/ADT/DenseMap.h"
16
17
18namespace lldb_private {
19
20template <typename _KeyType, typename _ValueType,
21          typename _MutexType = std::mutex>
22class ThreadSafeDenseMap {
23public:
24  typedef llvm::DenseMap<_KeyType, _ValueType> LLVMMapType;
25
26  ThreadSafeDenseMap(unsigned map_initial_capacity = 0)
27      : m_map(map_initial_capacity), m_mutex() {}
28
29  void Insert(_KeyType k, _ValueType v) {
30    std::lock_guard<_MutexType> guard(m_mutex);
31    m_map.insert(std::make_pair(k, v));
32  }
33
34  void Erase(_KeyType k) {
35    std::lock_guard<_MutexType> guard(m_mutex);
36    m_map.erase(k);
37  }
38
39  _ValueType Lookup(_KeyType k) {
40    std::lock_guard<_MutexType> guard(m_mutex);
41    return m_map.lookup(k);
42  }
43
44  bool Lookup(_KeyType k, _ValueType &v) {
45    std::lock_guard<_MutexType> guard(m_mutex);
46    auto iter = m_map.find(k), end = m_map.end();
47    if (iter == end)
48      return false;
49    v = iter->second;
50    return true;
51  }
52
53  void Clear() {
54    std::lock_guard<_MutexType> guard(m_mutex);
55    m_map.clear();
56  }
57
58protected:
59  LLVMMapType m_map;
60  _MutexType m_mutex;
61};
62
63} // namespace lldb_private
64
65#endif // liblldb_ThreadSafeDenseMap_h_
66