Blender V5.0
BLI_shared_cache.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#pragma once
10
11#include "BLI_cache_mutex.hh"
12
13#include <memory>
14
15namespace blender {
16
35template<typename T> class SharedCache {
36 struct CacheData {
38 T data;
39 CacheData() = default;
40 CacheData(const T &data) : data(data) {}
41 };
42 std::shared_ptr<CacheData> cache_;
43
44 public:
46 {
47 /* The cache should be allocated to trigger sharing of the cached data as early as possible. */
48 cache_ = std::make_shared<CacheData>();
49 }
50
52 void tag_dirty()
53 {
54 if (cache_.use_count() == 1) {
55 cache_->mutex.tag_dirty();
56 }
57 else {
58 cache_ = std::make_shared<CacheData>();
59 }
60 }
61
66 void ensure(FunctionRef<void(T &data)> compute_cache)
67 {
68 cache_->mutex.ensure([&]() { compute_cache(this->cache_->data); });
69 }
70
77 void update(FunctionRef<void(T &data)> compute_cache)
78 {
79 if (cache_.use_count() == 1) {
80 cache_->mutex.tag_dirty();
81 }
82 else {
83 cache_ = std::make_shared<CacheData>(cache_->data);
84 }
85 cache_->mutex.ensure([&]() { compute_cache(this->cache_->data); });
86 }
87
89 const T &data() const
90 {
91 BLI_assert(cache_->mutex.is_cached());
92 return cache_->data;
93 }
94
98 bool is_dirty() const
99 {
100 return cache_->mutex.is_dirty();
101 }
102
106 bool is_cached() const
107 {
108 return cache_->mutex.is_cached();
109 }
110};
111
112} // namespace blender
#define BLI_assert(a)
Definition BLI_assert.h:46
void update(FunctionRef< void(T &data)> compute_cache)
void ensure(FunctionRef< void(T &data)> compute_cache)
const T & data() const
ThreadMutex mutex
#define T