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