forked from flutter/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread_local.h
131 lines (90 loc) · 2.55 KB
/
thread_local.h
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
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_THREAD_LOCAL_H_
#define FLUTTER_FML_THREAD_LOCAL_H_
#include <functional>
#include "flutter/fml/build_config.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/macros.h"
#define FML_THREAD_LOCAL_PTHREADS OS_MACOSX || OS_LINUX || OS_ANDROID
#if FML_THREAD_LOCAL_PTHREADS
#include <pthread.h>
#endif
namespace fml {
using ThreadLocalDestroyCallback = std::function<void(intptr_t)>;
#if FML_THREAD_LOCAL_PTHREADS
// thread_local is unavailable and we have to resort to pthreads.
#define FML_THREAD_LOCAL static
class ThreadLocal {
private:
class Box {
public:
Box(ThreadLocalDestroyCallback destroy, intptr_t value);
~Box();
intptr_t Value() const { return value_; }
void SetValue(intptr_t value) {
if (value == value_) {
return;
}
DestroyValue();
value_ = value;
}
void DestroyValue() {
if (destroy_) {
destroy_(value_);
}
}
private:
ThreadLocalDestroyCallback destroy_;
intptr_t value_;
FML_DISALLOW_COPY_AND_ASSIGN(Box);
};
static inline void ThreadLocalDestroy(void* value) {
FML_CHECK(value != nullptr);
auto* box = reinterpret_cast<Box*>(value);
box->DestroyValue();
delete box;
}
public:
ThreadLocal();
ThreadLocal(ThreadLocalDestroyCallback destroy);
void Set(intptr_t value) {
auto* box = reinterpret_cast<Box*>(pthread_getspecific(_key));
if (box == nullptr) {
box = new Box(destroy_, value);
FML_CHECK(pthread_setspecific(_key, box) == 0);
} else {
box->SetValue(value);
}
}
intptr_t Get() {
auto* box = reinterpret_cast<Box*>(pthread_getspecific(_key));
return box != nullptr ? box->Value() : 0;
}
~ThreadLocal();
private:
pthread_key_t _key;
ThreadLocalDestroyCallback destroy_;
FML_DISALLOW_COPY_AND_ASSIGN(ThreadLocal);
};
#else // FML_THREAD_LOCAL_PTHREADS
#define FML_THREAD_LOCAL thread_local
class ThreadLocal {
public:
ThreadLocal();
ThreadLocal(ThreadLocalDestroyCallback destroy);
void Set(intptr_t value);
intptr_t Get();
~ThreadLocal();
private:
ThreadLocalDestroyCallback destroy_;
intptr_t value_;
FML_DISALLOW_COPY_AND_ASSIGN(ThreadLocal);
};
#endif // FML_THREAD_LOCAL_PTHREADS
#ifndef FML_THREAD_LOCAL
#error Thread local storage unavailable on the platform.
#endif // FML_THREAD_LOCAL
} // namespace fml
#endif // FLUTTER_FML_THREAD_LOCAL_H_