blob: cd55ad43b9187c4a1f4984f90cc4a8be72ea3102 [file] [log] [blame]
Yifan Hong84888d32017-02-06 15:32:41 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef ANDROID_HIDL_CONCURRENT_MAP_H
17#define ANDROID_HIDL_CONCURRENT_MAP_H
18
19#include <mutex>
20#include <map>
21
22namespace android {
23namespace hardware {
24
25template<typename K, typename V>
26class ConcurrentMap {
27private:
28 using size_type = typename std::map<K, V>::size_type;
29 using iterator = typename std::map<K, V>::iterator;
30 using const_iterator = typename std::map<K, V>::const_iterator;
31
32public:
33 void set(K &&k, V &&v) {
34 std::unique_lock<std::mutex> _lock(mMutex);
35 mMap[std::forward<K>(k)] = std::forward<V>(v);
36 }
37
38 // get with the given default value.
39 const V &get(const K &k, const V &def) const {
40 std::unique_lock<std::mutex> _lock(mMutex);
41 const_iterator iter = mMap.find(k);
42 if (iter == mMap.end()) {
43 return def;
44 }
45 return iter->second;
46 }
47
48 size_type erase(const K &k) {
49 std::unique_lock<std::mutex> _lock(mMutex);
50 return mMap.erase(k);
51 }
52
Steven Morelande67a6762017-05-16 14:53:28 -070053 std::unique_lock<std::mutex> lock() { return std::unique_lock<std::mutex>(mMutex); }
54
55 void setLocked(K&& k, V&& v) { mMap[std::forward<K>(k)] = std::forward<V>(v); }
56
57 const V& getLocked(const K& k, const V& def) const {
58 const_iterator iter = mMap.find(k);
59 if (iter == mMap.end()) {
60 return def;
61 }
62 return iter->second;
63 }
64
65 private:
Yifan Hong84888d32017-02-06 15:32:41 -080066 mutable std::mutex mMutex;
67 std::map<K, V> mMap;
68};
69
70} // namespace hardware
71} // namespace android
72
73
74#endif // ANDROID_HIDL_CONCURRENT_MAP_H