Blender V5.3
BLI_enumerable_thread_specific.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#ifdef WITH_TBB
12# include <tbb/enumerable_thread_specific.h>
13#else
14# include <atomic>
15# include <functional>
16
17# include "BLI_map.hh"
18# include "BLI_mutex.hh"
19#endif
20
21#include "BLI_utility_mixins.hh"
22
24
25#ifndef WITH_TBB
27inline std::atomic<int> next_id = 0;
28inline thread_local int thread_id = next_id.fetch_add(1, std::memory_order_relaxed);
29} // namespace enumerable_thread_specific_utils
30#endif /* !WITH_TBB */
31
38template<typename T> class EnumerableThreadSpecific : NonCopyable, NonMovable {
39#ifdef WITH_TBB
40
41 private:
42 tbb::enumerable_thread_specific<T> values_;
43
44 public:
45 using iterator = typename tbb::enumerable_thread_specific<T>::iterator;
46
47 EnumerableThreadSpecific() = default;
48
49 template<typename F> EnumerableThreadSpecific(F initializer) : values_(std::move(initializer)) {}
50
51 T &local()
52 {
53 return values_.local();
54 }
55
57 {
58 return values_.begin();
59 }
60
62 {
63 return values_.end();
64 }
65
66#else /* WITH_TBB */
67
68 private:
69 Mutex mutex_;
70 /* Maps thread ids to their corresponding values. The values are not embedded in the map, so that
71 * their addresses do not change when the map grows. */
73 Vector<std::unique_ptr<T>> owned_values_;
74 std::function<void(void *)> initializer_;
75
76 public:
77 using iterator = typename Map<int, std::reference_wrapper<T>>::MutableValueIterator;
78
79 EnumerableThreadSpecific() : initializer_([](void *buffer) { new (buffer) T(); }) {}
80
81 template<typename F>
83 : initializer_([=](void *buffer) { new (buffer) T(initializer()); })
84 {
85 }
86
88 {
90 std::lock_guard lock{mutex_};
91 return values_.lookup_or_add_cb(thread_id, [&]() {
92 T *value = static_cast<T *>(::operator new(sizeof(T)));
93 initializer_(value);
94 owned_values_.append(std::unique_ptr<T>{value});
95 return std::reference_wrapper<T>{*value};
96 });
97 }
98
100 {
101 return values_.values().begin();
102 }
103
105 {
106 return values_.values().end();
107 }
108
109#endif /* WITH_TBB */
110};
111
112} // namespace blender::threading
volatile int lock
NonCopyable(const NonCopyable &other)=delete
NonMovable(NonMovable &&other)=delete
typename Map< int, std::reference_wrapper< T > >::MutableValueIterator iterator
#define T
#define F
std::mutex Mutex
Definition BLI_mutex.hh:51