blob: a1cab8db5a71bd0601e92f4c81b889635e47eaa7 [file] [log] [blame]
Jiawei Shao94d16782021-10-29 01:12:25 +00001// 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
24template <typename T>
25class ConcurrentCache : public NonMovable {
26 public:
27 ConcurrentCache() = default;
28
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
38 std::pair<T*, bool> Insert(T* object) {
39 std::lock_guard<std::mutex> lock(mMutex);
Corentin Wallez5984d8d2022-01-06 09:17:57 +000040 auto [value, inserted] = mCache.insert(object);
41 return {*value, inserted};
Jiawei Shao94d16782021-10-29 01:12:25 +000042 }
43
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