Jiawei Shao | 94d1678 | 2021-10-29 01:12:25 +0000 | [diff] [blame] | 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 | |
| 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 Wallez | 5984d8d | 2022-01-06 09:17:57 +0000 | [diff] [blame] | 40 | auto [value, inserted] = mCache.insert(object); |
| 41 | return {*value, inserted}; |
Jiawei Shao | 94d1678 | 2021-10-29 01:12:25 +0000 | [diff] [blame] | 42 | } |
| 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 |