forked from flutter/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread_local.h
87 lines (56 loc) · 1.75 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
// 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 <memory>
#include "flutter/fml/build_config.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 {
#if FML_THREAD_LOCAL_PTHREADS
#define FML_THREAD_LOCAL static
namespace internal {
class ThreadLocalPointer {
public:
ThreadLocalPointer(void (*destroy)(void*));
~ThreadLocalPointer();
void* get() const;
void* swap(void* ptr);
private:
pthread_key_t key_;
FML_DISALLOW_COPY_AND_ASSIGN(ThreadLocalPointer);
};
} // namespace internal
template <typename T>
class ThreadLocalUniquePtr {
public:
ThreadLocalUniquePtr() : ptr_(destroy) {}
T* get() const { return reinterpret_cast<T*>(ptr_.get()); }
void reset(T* ptr) { destroy(ptr_.swap(ptr)); }
private:
static void destroy(void* ptr) { delete reinterpret_cast<T*>(ptr); }
internal::ThreadLocalPointer ptr_;
FML_DISALLOW_COPY_AND_ASSIGN(ThreadLocalUniquePtr);
};
#else // FML_THREAD_LOCAL_PTHREADS
#define FML_THREAD_LOCAL static thread_local
template <typename T>
class ThreadLocalUniquePtr {
public:
ThreadLocalUniquePtr() = default;
T* get() const { return ptr_.get(); }
void reset(T* ptr) { ptr_.reset(ptr); }
private:
std::unique_ptr<T> ptr_;
FML_DISALLOW_COPY_AND_ASSIGN(ThreadLocalUniquePtr);
};
#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_