blob: 1d580dc238bfdcc8506754c98f3e7f1810b90311 (
plain)
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
|
#ifndef MBGL_UTIL_THREAD_LOCAL
#define MBGL_UTIL_THREAD_LOCAL
#include <mbgl/util/noncopyable.hpp>
#include <stdexcept>
#include <pthread.h>
namespace mbgl {
namespace util {
template <class T>
class ThreadLocal : public noncopyable {
public:
inline ThreadLocal(T* val) {
ThreadLocal();
set(val);
}
inline ThreadLocal() {
int ret = pthread_key_create(&key, [](void *ptr) {
delete reinterpret_cast<T *>(ptr);
});
if (ret) {
throw new std::runtime_error("Failed to init local storage key.");
}
}
inline ~ThreadLocal() {
if (pthread_key_delete(key)) {
throw new std::runtime_error("Failed to delete local storage key.");
}
}
inline T* get() {
T* ret = reinterpret_cast<T*>(pthread_getspecific(key));
if (!ret) {
return nullptr;
}
return ret;
}
inline void set(T* ptr) {
if (pthread_setspecific(key, ptr)) {
throw new std::runtime_error("Failed to set local storage.");
}
}
private:
pthread_key_t key;
};
}
}
#endif
|