| 52 | struct SharedCache |
| 53 | { |
| 54 | std::shared_ptr<T> acquire(Key key, const std::function<std::shared_ptr<T>()>& init) |
| 55 | { |
| 56 | std::lock_guard<std::mutex> lock(mutex); |
| 57 | auto it = cache.find(key); |
| 58 | if (it != cache.end()) |
| 59 | { |
| 60 | if (auto data = it->second.lock()) |
| 61 | return data; |
| 62 | else |
| 63 | cache.erase(it); |
| 64 | } |
| 65 | |
| 66 | std::shared_ptr<T> data = init(); |
| 67 | cache.emplace(key, data); |
| 68 | return data; |
| 69 | } |
| 70 | |
| 71 | std::mutex mutex; |
| 72 | std::map<Key, std::weak_ptr<T>> cache; |