ThreadLocal.h
Go to the documentation of this file.
1 // This file is part of Eigen, a lightweight C++ template library
2 // for linear algebra.
3 //
4 // Copyright (C) 2016 Benoit Steiner <benoit.steiner.goog@gmail.com>
5 //
6 // This Source Code Form is subject to the terms of the Mozilla
7 // Public License v. 2.0. If a copy of the MPL was not distributed
8 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 
10 #ifndef EIGEN_CXX11_THREADPOOL_THREAD_LOCAL_H
11 #define EIGEN_CXX11_THREADPOOL_THREAD_LOCAL_H
12 
13 #ifdef EIGEN_AVOID_THREAD_LOCAL
14 
15 #ifdef EIGEN_THREAD_LOCAL
16 #undef EIGEN_THREAD_LOCAL
17 #endif
18 
19 #else
20 
21 #if ((EIGEN_COMP_GNUC) || __has_feature(cxx_thread_local) || EIGEN_COMP_MSVC )
22 #define EIGEN_THREAD_LOCAL static thread_local
23 #endif
24 
25 // Disable TLS for Apple and Android builds with older toolchains.
26 #if defined(__APPLE__)
27 // Included for TARGET_OS_IPHONE, __IPHONE_OS_VERSION_MIN_REQUIRED,
28 // __IPHONE_8_0.
29 #include <Availability.h>
30 #include <TargetConditionals.h>
31 #endif
32 // Checks whether C++11's `thread_local` storage duration specifier is
33 // supported.
34 #if EIGEN_COMP_CLANGAPPLE && ((EIGEN_COMP_CLANGAPPLE < 8000042) || \
35  (TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_9_0))
36 // Notes: Xcode's clang did not support `thread_local` until version
37 // 8, and even then not for all iOS < 9.0.
38 #undef EIGEN_THREAD_LOCAL
39 
40 #elif defined(__ANDROID__) && EIGEN_COMP_CLANG
41 // There are platforms for which TLS should not be used even though the compiler
42 // makes it seem like it's supported (Android NDK < r12b for example).
43 // This is primarily because of linker problems and toolchain misconfiguration:
44 // TLS isn't supported until NDK r12b per
45 // https://developer.android.com/ndk/downloads/revision_history.html
46 // Since NDK r16, `__NDK_MAJOR__` and `__NDK_MINOR__` are defined in
47 // <android/ndk-version.h>. For NDK < r16, users should define these macros,
48 // e.g. `-D__NDK_MAJOR__=11 -D__NKD_MINOR__=0` for NDK r11.
49 #if __has_include(<android/ndk-version.h>)
50 #include <android/ndk-version.h>
51 #endif // __has_include(<android/ndk-version.h>)
52 #if defined(__ANDROID__) && defined(__clang__) && defined(__NDK_MAJOR__) && \
53  defined(__NDK_MINOR__) && \
54  ((__NDK_MAJOR__ < 12) || ((__NDK_MAJOR__ == 12) && (__NDK_MINOR__ < 1)))
55 #undef EIGEN_THREAD_LOCAL
56 #endif
57 #endif // defined(__ANDROID__) && defined(__clang__)
58 
59 #endif // EIGEN_AVOID_THREAD_LOCAL
60 
61 #include "./InternalHeaderCheck.h"
62 
63 namespace Eigen {
64 
65 namespace internal {
66 template <typename T>
67 struct ThreadLocalNoOpInitialize {
68  void operator()(T&) const {}
69 };
70 
71 template <typename T>
72 struct ThreadLocalNoOpRelease {
73  void operator()(T&) const {}
74 };
75 
76 } // namespace internal
77 
78 // Thread local container for elements of type T, that does not use thread local
79 // storage. As long as the number of unique threads accessing this storage
80 // is smaller than `capacity_`, it is lock-free and wait-free. Otherwise it will
81 // use a mutex for synchronization.
82 //
83 // Type `T` has to be default constructible, and by default each thread will get
84 // a default constructed value. It is possible to specify custom `initialize`
85 // callable, that will be called lazily from each thread accessing this object,
86 // and will be passed a default initialized object of type `T`. Also it's
87 // possible to pass a custom `release` callable, that will be invoked before
88 // calling ~T().
89 //
90 // Example:
91 //
92 // struct Counter {
93 // int value = 0;
94 // }
95 //
96 // Eigen::ThreadLocal<Counter> counter(10);
97 //
98 // // Each thread will have access to it's own counter object.
99 // Counter& cnt = counter.local();
100 // cnt++;
101 //
102 // WARNING: Eigen::ThreadLocal uses the OS-specific value returned by
103 // std::this_thread::get_id() to identify threads. This value is not guaranteed
104 // to be unique except for the life of the thread. A newly created thread may
105 // get an OS-specific ID equal to that of an already destroyed thread.
106 //
107 // Somewhat similar to TBB thread local storage, with similar restrictions:
108 // https://www.threadingbuildingblocks.org/docs/help/reference/thread_local_storage/enumerable_thread_specific_cls.html
109 //
110 template <typename T,
111  typename Initialize = internal::ThreadLocalNoOpInitialize<T>,
112  typename Release = internal::ThreadLocalNoOpRelease<T>>
113 class ThreadLocal {
114  // We preallocate default constructed elements in MaxSizedVector.
115  static_assert(std::is_default_constructible<T>::value,
116  "ThreadLocal data type must be default constructible");
117 
118  public:
119  explicit ThreadLocal(int capacity)
120  : ThreadLocal(capacity, internal::ThreadLocalNoOpInitialize<T>(),
121  internal::ThreadLocalNoOpRelease<T>()) {}
122 
123  ThreadLocal(int capacity, Initialize initialize)
124  : ThreadLocal(capacity, std::move(initialize),
125  internal::ThreadLocalNoOpRelease<T>()) {}
126 
127  ThreadLocal(int capacity, Initialize initialize, Release release)
128  : initialize_(std::move(initialize)),
129  release_(std::move(release)),
130  capacity_(capacity),
131  data_(capacity_),
132  ptr_(capacity_),
133  filled_records_(0) {
134  eigen_assert(capacity_ >= 0);
135  data_.resize(capacity_);
136  for (int i = 0; i < capacity_; ++i) {
137  ptr_.emplace_back(nullptr);
138  }
139  }
140 
141  T& local() {
142  std::thread::id this_thread = std::this_thread::get_id();
143  if (capacity_ == 0) return SpilledLocal(this_thread);
144 
145  std::size_t h = std::hash<std::thread::id>()(this_thread);
146  const int start_idx = h % capacity_;
147 
148  // NOTE: From the definition of `std::this_thread::get_id()` it is
149  // guaranteed that we never can have concurrent insertions with the same key
150  // to our hash-map like data structure. If we didn't find an element during
151  // the initial traversal, it's guaranteed that no one else could have
152  // inserted it while we are in this function. This allows to massively
153  // simplify out lock-free insert-only hash map.
154 
155  // Check if we already have an element for `this_thread`.
156  int idx = start_idx;
157  while (ptr_[idx].load() != nullptr) {
158  ThreadIdAndValue& record = *(ptr_[idx].load());
159  if (record.thread_id == this_thread) return record.value;
160 
161  idx += 1;
162  if (idx >= capacity_) idx -= capacity_;
163  if (idx == start_idx) break;
164  }
165 
166  // If we are here, it means that we found an insertion point in lookup
167  // table at `idx`, or we did a full traversal and table is full.
168 
169  // If lock-free storage is full, fallback on mutex.
170  if (filled_records_.load() >= capacity_) return SpilledLocal(this_thread);
171 
172  // We double check that we still have space to insert an element into a lock
173  // free storage. If old value in `filled_records_` is larger than the
174  // records capacity, it means that some other thread added an element while
175  // we were traversing lookup table.
176  int insertion_index =
177  filled_records_.fetch_add(1, std::memory_order_relaxed);
178  if (insertion_index >= capacity_) return SpilledLocal(this_thread);
179 
180  // At this point it's guaranteed that we can access to
181  // data_[insertion_index_] without a data race.
182  data_[insertion_index].thread_id = this_thread;
183  initialize_(data_[insertion_index].value);
184 
185  // That's the pointer we'll put into the lookup table.
186  ThreadIdAndValue* inserted = &data_[insertion_index];
187 
188  // We'll use nullptr pointer to ThreadIdAndValue in a compare-and-swap loop.
189  ThreadIdAndValue* empty = nullptr;
190 
191  // Now we have to find an insertion point into the lookup table. We start
192  // from the `idx` that was identified as an insertion point above, it's
193  // guaranteed that we will have an empty record somewhere in a lookup table
194  // (because we created a record in the `data_`).
195  const int insertion_idx = idx;
196 
197  do {
198  // Always start search from the original insertion candidate.
199  idx = insertion_idx;
200  while (ptr_[idx].load() != nullptr) {
201  idx += 1;
202  if (idx >= capacity_) idx -= capacity_;
203  // If we did a full loop, it means that we don't have any free entries
204  // in the lookup table, and this means that something is terribly wrong.
205  eigen_assert(idx != insertion_idx);
206  }
207  // Atomic CAS of the pointer guarantees that any other thread, that will
208  // follow this pointer will see all the mutations in the `data_`.
209  } while (!ptr_[idx].compare_exchange_weak(empty, inserted));
210 
211  return inserted->value;
212  }
213 
214  // WARN: It's not thread safe to call it concurrently with `local()`.
215  void ForEach(std::function<void(std::thread::id, T&)> f) {
216  // Reading directly from `data_` is unsafe, because only CAS to the
217  // record in `ptr_` makes all changes visible to other threads.
218  for (auto& ptr : ptr_) {
219  ThreadIdAndValue* record = ptr.load();
220  if (record == nullptr) continue;
221  f(record->thread_id, record->value);
222  }
223 
224  // We did not spill into the map based storage.
225  if (filled_records_.load(std::memory_order_relaxed) < capacity_) return;
226 
227  // Adds a happens before edge from the last call to SpilledLocal().
228  EIGEN_MUTEX_LOCK lock(mu_);
229  for (auto& kv : per_thread_map_) {
230  f(kv.first, kv.second);
231  }
232  }
233 
234  // WARN: It's not thread safe to call it concurrently with `local()`.
236  // Reading directly from `data_` is unsafe, because only CAS to the record
237  // in `ptr_` makes all changes visible to other threads.
238  for (auto& ptr : ptr_) {
239  ThreadIdAndValue* record = ptr.load();
240  if (record == nullptr) continue;
241  release_(record->value);
242  }
243 
244  // We did not spill into the map based storage.
245  if (filled_records_.load(std::memory_order_relaxed) < capacity_) return;
246 
247  // Adds a happens before edge from the last call to SpilledLocal().
248  EIGEN_MUTEX_LOCK lock(mu_);
249  for (auto& kv : per_thread_map_) {
250  release_(kv.second);
251  }
252  }
253 
254  private:
256  std::thread::id thread_id;
258  };
259 
260  // Use unordered map guarded by a mutex when lock free storage is full.
261  T& SpilledLocal(std::thread::id this_thread) {
262  EIGEN_MUTEX_LOCK lock(mu_);
263 
264  auto it = per_thread_map_.find(this_thread);
265  if (it == per_thread_map_.end()) {
266  auto result = per_thread_map_.emplace(this_thread, T());
267  eigen_assert(result.second);
268  initialize_((*result.first).second);
269  return (*result.first).second;
270  } else {
271  return it->second;
272  }
273  }
274 
275  Initialize initialize_;
276  Release release_;
277  const int capacity_;
278 
279  // Storage that backs lock-free lookup table `ptr_`. Records stored in this
280  // storage contiguously starting from index 0.
282 
283  // Atomic pointers to the data stored in `data_`. Used as a lookup table for
284  // linear probing hash map (https://en.wikipedia.org/wiki/Linear_probing).
286 
287  // Number of records stored in the `data_`.
288  std::atomic<int> filled_records_;
289 
290  // We fallback on per thread map if lock-free storage is full. In practice
291  // this should never happen, if `capacity_` is a reasonable estimate of the
292  // number of threads running in a system.
293  EIGEN_MUTEX mu_; // Protects per_thread_map_.
294  std::unordered_map<std::thread::id, T> per_thread_map_;
295 };
296 
297 } // namespace Eigen
298 
299 #endif // EIGEN_CXX11_THREADPOOL_THREAD_LOCAL_H
IndexedView_or_Block operator()(const RowIndices &rowIndices, const ColIndices &colIndices)
#define eigen_assert(x)
Definition: Macros.h:902
#define EIGEN_MUTEX
Definition: ThreadPool:55
#define EIGEN_MUTEX_LOCK
Definition: ThreadPool:58
Eigen::Triplet< double > T
The MaxSizeVector class.
Definition: MaxSizeVector.h:31
T & SpilledLocal(std::thread::id this_thread)
Definition: ThreadLocal.h:261
ThreadLocal(int capacity)
Definition: ThreadLocal.h:119
Initialize initialize_
Definition: ThreadLocal.h:275
ThreadLocal(int capacity, Initialize initialize)
Definition: ThreadLocal.h:123
void ForEach(std::function< void(std::thread::id, T &)> f)
Definition: ThreadLocal.h:215
MaxSizeVector< ThreadIdAndValue > data_
Definition: ThreadLocal.h:281
MaxSizeVector< std::atomic< ThreadIdAndValue * > > ptr_
Definition: ThreadLocal.h:285
EIGEN_MUTEX mu_
Definition: ThreadLocal.h:293
std::atomic< int > filled_records_
Definition: ThreadLocal.h:288
const int capacity_
Definition: ThreadLocal.h:277
ThreadLocal(int capacity, Initialize initialize, Release release)
Definition: ThreadLocal.h:127
std::unordered_map< std::thread::id, T > per_thread_map_
Definition: ThreadLocal.h:294
: InteropHeaders
Definition: Core:139
Definition: BFloat16.h:222