• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 LLDB_CORE_THREADSAFEDENSEMAP_H
11 #define LLDB_CORE_THREADSAFEDENSEMAP_H
12 
13 #include <mutex>
14 
15 #include "llvm/ADT/DenseMap.h"
16 
17 
18 namespace lldb_private {
19 
20 template <typename _KeyType, typename _ValueType,
21           typename _MutexType = std::mutex>
22 class ThreadSafeDenseMap {
23 public:
24   typedef llvm::DenseMap<_KeyType, _ValueType> LLVMMapType;
25 
26   ThreadSafeDenseMap(unsigned map_initial_capacity = 0)
m_map(map_initial_capacity)27       : m_map(map_initial_capacity), m_mutex() {}
28 
Insert(_KeyType k,_ValueType v)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 
Erase(_KeyType k)34   void Erase(_KeyType k) {
35     std::lock_guard<_MutexType> guard(m_mutex);
36     m_map.erase(k);
37   }
38 
Lookup(_KeyType k)39   _ValueType Lookup(_KeyType k) {
40     std::lock_guard<_MutexType> guard(m_mutex);
41     return m_map.lookup(k);
42   }
43 
Lookup(_KeyType k,_ValueType & v)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 
Clear()53   void Clear() {
54     std::lock_guard<_MutexType> guard(m_mutex);
55     m_map.clear();
56   }
57 
58 protected:
59   LLVMMapType m_map;
60   _MutexType m_mutex;
61 };
62 
63 } // namespace lldb_private
64 
65 #endif // LLDB_CORE_THREADSAFEDENSEMAP_H
66