• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Dawn Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef COMMON_CONCURRENT_CACHE_H_
16 #define COMMON_CONCURRENT_CACHE_H_
17 
18 #include "common/NonCopyable.h"
19 
20 #include <mutex>
21 #include <unordered_set>
22 #include <utility>
23 
24 template <typename T>
25 class ConcurrentCache : public NonMovable {
26   public:
27     ConcurrentCache() = default;
28 
Find(T * object)29     T* Find(T* object) {
30         std::lock_guard<std::mutex> lock(mMutex);
31         auto iter = mCache.find(object);
32         if (iter == mCache.end()) {
33             return nullptr;
34         }
35         return *iter;
36     }
37 
Insert(T * object)38     std::pair<T*, bool> Insert(T* object) {
39         std::lock_guard<std::mutex> lock(mMutex);
40         auto insertion = mCache.insert(object);
41         return std::make_pair(*(insertion.first), insertion.second);
42     }
43 
Erase(T * object)44     size_t Erase(T* object) {
45         std::lock_guard<std::mutex> lock(mMutex);
46         return mCache.erase(object);
47     }
48 
49   private:
50     std::mutex mMutex;
51     std::unordered_set<T*, typename T::HashFunc, typename T::EqualityFunc> mCache;
52 };
53 
54 #endif
55