Wildmeshing Toolkit
Loading...
Searching...
No Matches
concurrent_map.hpp
1#pragma once
2
3#include <map>
4#include <mutex>
5#include <unordered_map>
6
7namespace wmtk::threading {
8
9namespace detail {
10template <typename MapType>
12{
13protected:
14 MapType m_map;
15 mutable std::mutex m_mutex;
16
17public:
18 using key_type = typename MapType::key_type;
19 using mapped_type = typename MapType::mapped_type;
20 using value_type = typename MapType::value_type;
21 using iterator = typename MapType::iterator;
22 using const_iterator = typename MapType::const_iterator;
23
24 concurrent_associative() = default;
25
26 // std::map / std::unordered_map keep references to elements valid across
27 // inserts, so returning a reference under a short structural lock is safe to
28 // use afterwards without holding the lock (matches TBB semantics; concurrent
29 // writes to the *same* element remain the caller's responsibility, as in TBB).
30 mapped_type& operator[](const key_type& k)
31 {
32 std::lock_guard<std::mutex> lock(m_mutex);
33 return m_map[k];
34 }
35
36 iterator find(const key_type& k)
37 {
38 std::lock_guard<std::mutex> lock(m_mutex);
39 return m_map.find(k);
40 }
41 const_iterator find(const key_type& k) const
42 {
43 std::lock_guard<std::mutex> lock(m_mutex);
44 return m_map.find(k);
45 }
46
47 std::size_t count(const key_type& k) const
48 {
49 std::lock_guard<std::mutex> lock(m_mutex);
50 return m_map.count(k);
51 }
52
53 iterator begin() { return m_map.begin(); }
54 iterator end() { return m_map.end(); }
55 const_iterator begin() const { return m_map.begin(); }
56 const_iterator end() const { return m_map.end(); }
57
58 std::size_t size() const { return m_map.size(); }
59 bool empty() const { return m_map.empty(); }
60 void clear() { m_map.clear(); }
61};
62} // namespace detail
63
64template <typename Key, typename T, typename Compare = std::less<Key>>
65class concurrent_map : public detail::concurrent_associative<std::map<Key, T, Compare>>
66{
67};
68
69template <typename Key, typename T, typename Hash = std::hash<Key>>
71 : public detail::concurrent_associative<std::unordered_map<Key, T, Hash>>
72{
73};
74
75} // namespace wmtk::threading
Definition concurrent_map.hpp:66
Definition concurrent_map.hpp:72
Definition concurrent_map.hpp:12