1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
|
#pragma once
#include <util/generic/deque.h>
#include <util/generic/hash.h>
#include <util/generic/hash_set.h>
#include <util/generic/maybe.h>
#include <util/generic/ptr.h>
#include <util/generic/vector.h>
#include <util/memory/pool.h>
#include <util/system/mutex.h>
#include <util/system/thread.h>
#include <library/cpp/threading/hot_swap/hot_swap.h>
#include <library/cpp/threading/skip_list/skiplist.h>
#include <array>
#include <atomic>
#include <thread>
namespace NThreading {
// TThreadLocalValue
//
// Safe RAII-friendly thread local storage without dirty hacks from util/system/tls
//
// Example 1:
//
// THolder<IThreadPool> pool = CreateThreadPool(threads);
// TThreadLocalValue<ui32> tls;
// for (ui32 i : xrange(threads)) {
// pool->SafeAddFunc([&]) {
// *tls->Get() = 1337;
// }
// }
//
// Example 2:
//
// class TNoisy {
// public:
// TNoisy(const char* name = "TNoisy")
// : Name_{name} {
// printf("%s::%s\n", Name_, Name_);
// }
//
// ~TNoisy() {
// printf("%s::~%s\n", Name_, Name_);
// }
// private:
// const char* Name_;
// };
//
// class TWrapper {
// public:
// TWrapper() {
// Println(__PRETTY_FUNCTION__);
// }
//
// ~TWrapper() {
// Println(__PRETTY_FUNCTION__);
// }
//
// void DoWork() {
// ThreadLocal_->Get();
// }
//
// private:
// TNoisy Noisy_{"TWrapper"};
// TThreadLocalValue<TNoisy> ThreadLocal_;
// };
//
// THolder<IThreadPool> pool = CreateThreadPool(3);
// {
// TWrapper wrapper;
// for (ui32 i : xrange(3)) {
// pool->SafeAddFunc([&] {
// wrapper.DoWork();
// });
// }
// }
//
// Will always print:
// TWrapper::TWrapper()
// TNoisy::TNoisy()
// TNoisy::TNoisy()
// TNoisy::TNoisy()
// TNoisy::~TNoisy()
// TNoisy::~TNoisy()
// TNoisy::~TNoisy()
// TWrapper::~TWrapper()
//
enum class EThreadLocalImpl {
HotSwap,
SkipList,
ForwardList,
StdThreadLocal // completely different implementation over thread_local keyword, correctly destroys objects on thread finish
};
namespace NDetail {
template <typename T, EThreadLocalImpl Impl, size_t NumShards>
class TThreadLocalValueImpl;
} // namespace NDetail
inline constexpr size_t DefaultNumShards = 3;
template <typename T, EThreadLocalImpl Impl = EThreadLocalImpl::SkipList, size_t NumShards = DefaultNumShards>
class TThreadLocalValue : private TNonCopyable {
public:
template <typename ...ConstructArgs>
T& GetRef(ConstructArgs&& ...args) const {
return *Get(std::forward<ConstructArgs>(args)...);
}
template <typename ...ConstructArgs>
T* Get(ConstructArgs&& ...args) const {
TThread::TId tid = TThread::CurrentThreadId();
return Shards_[tid % NumShards].Get(tid, std::forward<ConstructArgs>(args)...);
}
private:
using TStorage = NDetail::TThreadLocalValueImpl<T, Impl, NumShards>;
mutable std::array<TStorage, NumShards> Shards_;
};
template <typename T, size_t NumShards>
class TThreadLocalValue<T, EThreadLocalImpl::StdThreadLocal, NumShards> : private TNonCopyable {
public:
~TThreadLocalValue() {
StaticState_->AllValues.Destroy(ObjectId_);
StaticState_->FlatIds.Put(ObjectId_);
}
template <typename ...ConstructArgs>
T& GetRef(ConstructArgs&& ...args) const {
return *Get(std::forward<ConstructArgs>(args)...);
}
template <typename ...ConstructArgs>
T* Get(ConstructArgs&& ...args) const {
auto& values = Values_.Storage;
with_lock (Values_.Lock) {
if (ObjectId_ >= values.size()) {
values.resize(ObjectId_ + 1);
}
}
TMaybe<T>& v = values[ObjectId_];
if (!v.Defined()) {
v.ConstructInPlace(std::forward<ConstructArgs>(args)...);
}
return &*v;
}
private:
struct TStaticState;
struct TPerThreadValues {
TAdaptiveLock Lock;
TDeque<TMaybe<T>> Storage;
public:
explicit TPerThreadValues(TAtomicSharedPtr<TStaticState> staticState)
: StaticState_(std::move(staticState))
{
StaticState_->AllValues.Add(this);
}
~TPerThreadValues() {
StaticState_->AllValues.Remove(this);
}
private:
TAtomicSharedPtr<TStaticState> StaticState_;
};
class TFlatIdGenerator {
public:
ui32 Get() {
with_lock (Lock_) {
if (Free_.empty()) {
return MaxUnused_++;
} else {
ui32 free = Free_.back();
Free_.pop_back();
return free;
}
}
}
void Put(ui32 id) {
with_lock (Lock_) {
Free_.push_back(id);
}
}
private:
TAdaptiveLock Lock_;
TVector<ui32> Free_;
ui32 MaxUnused_ = 0;
};
struct TAllValues {
public:
void Add(TPerThreadValues* v) {
with_lock (Lock_) {
Ptrs_.insert(v);
}
}
void Remove(TPerThreadValues* v) {
with_lock (Lock_) {
Ptrs_.erase(v);
}
}
void Destroy(ui32 objectId) {
with_lock (Lock_) {
for (auto* v : Ptrs_) {
TMaybe<T>* toDestroy = nullptr;
with_lock (v->Lock) {
if (objectId < v->Storage.size()) {
toDestroy = &v->Storage[objectId];
}
}
if (toDestroy) {
toDestroy->Clear();
}
}
}
}
private:
TAdaptiveLock Lock_;
THashSet<TPerThreadValues*> Ptrs_;
};
private:
struct TStaticState {
TFlatIdGenerator FlatIds;
TAllValues AllValues;
};
static TAtomicSharedPtr<TStaticState> GetStaticState() {
static TAtomicSharedPtr<TStaticState> state = MakeAtomicShared<TStaticState>();
return state;
}
private:
TAtomicSharedPtr<TStaticState> StaticState_ = GetStaticState();
const ui32 ObjectId_ = StaticState_->FlatIds.Get();
static inline thread_local TPerThreadValues Values_{GetStaticState()};
};
namespace NDetail {
template <typename T, size_t NumShards>
class TThreadLocalValueImpl<T, EThreadLocalImpl::HotSwap, NumShards> {
private:
class TStorage: public THashMap<TThread::TId, TAtomicSharedPtr<T>>, public TAtomicRefCount<TStorage> {
};
public:
TThreadLocalValueImpl() {
Registered_.AtomicStore(new TStorage());
}
template <typename ...ConstructArgs>
T* Get(TThread::TId tid, ConstructArgs&& ...args) {
if (TIntrusivePtr<TStorage> state = Registered_.AtomicLoad(); TAtomicSharedPtr<T>* result = state->FindPtr(tid)) {
return result->Get();
} else {
TAtomicSharedPtr<T> value = MakeAtomicShared<T>(std::forward<ConstructArgs>(args)...);
with_lock(RegisterLock_) {
TIntrusivePtr<TStorage> oldState = Registered_.AtomicLoad();
THolder<TStorage> newState = MakeHolder<TStorage>(*oldState);
(*newState)[tid] = value;
Registered_.AtomicStore(newState.Release());
}
return value.Get();
}
}
private:
THotSwap<TStorage> Registered_;
TMutex RegisterLock_;
};
template <typename T, size_t NumShards>
class TThreadLocalValueImpl<T, EThreadLocalImpl::SkipList, NumShards> {
private:
struct TNode {
TThread::TId Key;
THolder<T> Value;
};
struct TCompare {
int operator()(const TNode& lhs, const TNode& rhs) const {
return ::NThreading::TCompare<TThread::TId>{}(lhs.Key, rhs.Key);
}
};
public:
TThreadLocalValueImpl()
: ListPool_{InitialPoolSize()}
, SkipList_{ListPool_}
{}
template <typename ...ConstructArgs>
T* Get(TThread::TId tid, ConstructArgs&& ...args) {
TNode key{tid, {}};
auto iterator = SkipList_.SeekTo(key);
if (iterator.IsValid() && iterator.GetValue().Key == key.Key) {
return iterator.GetValue().Value.Get();
}
with_lock (RegisterLock_) {
SkipList_.Insert({tid, MakeHolder<T>(std::forward<ConstructArgs>(args)...)});
}
iterator = SkipList_.SeekTo(key);
return iterator.GetValue().Value.Get();
}
private:
static size_t InitialPoolSize() {
return std::thread::hardware_concurrency() * (sizeof(T) + sizeof(TThread::TId) + sizeof(void*)) / NumShards;
}
private:
static inline constexpr size_t MaxHeight = 6;
using TCustomSkipList = TSkipList<TNode, TCompare, TMemoryPool, TSizeCounter, MaxHeight>;
TMemoryPool ListPool_;
TCustomSkipList SkipList_;
TAdaptiveLock RegisterLock_;
};
template <typename T, size_t NumShards>
class TThreadLocalValueImpl<T, EThreadLocalImpl::ForwardList, NumShards> {
private:
struct TNode {
TThread::TId Key = 0;
T Value;
TNode* Next = nullptr;
};
public:
TThreadLocalValueImpl()
: Head_{nullptr}
, Pool_{0}
{}
template <typename ...ConstructArgs>
T* Get(TThread::TId tid, ConstructArgs&& ...args) {
TNode* head = Head_.load(std::memory_order_acquire);
for (TNode* node = head; node; node = node->Next) {
if (node->Key == tid) {
return &node->Value;
}
}
TNode* newNode = AllocateNode(tid, head, std::forward<ConstructArgs>(args)...);
while (!Head_.compare_exchange_weak(head, newNode, std::memory_order_release, std::memory_order_relaxed)) {
newNode->Next = head;
}
return &newNode->Value;
}
template <typename ...ConstructArgs>
TNode* AllocateNode(TThread::TId tid, TNode* next, ConstructArgs&& ...args) {
TNode* storage = nullptr;
with_lock(PoolMutex_) {
storage = Pool_.Allocate<TNode>();
}
new (storage) TNode{tid, T{std::forward<ConstructArgs>(args)...}, next};
return storage;
}
~TThreadLocalValueImpl() {
if constexpr (!std::is_trivially_destructible_v<T>) {
TNode* next = nullptr;
for (TNode* node = Head_.load(); node; node = next) {
next = node->Next;
node->~TNode();
}
}
}
private:
std::atomic<TNode*> Head_;
TMemoryPool Pool_;
TMutex PoolMutex_;
};
} // namespace NDetail
} // namespace NThreading
|