1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef FLUTTER_FML_THREAD_LOCAL_H_
6#define FLUTTER_FML_THREAD_LOCAL_H_
7
8#include <memory>
9
10#include "flutter/fml/build_config.h"
11#include "flutter/fml/macros.h"
12
13#define FML_THREAD_LOCAL_PTHREADS \
14 FML_OS_MACOSX || FML_OS_LINUX || FML_OS_ANDROID
15
16#if FML_THREAD_LOCAL_PTHREADS
17#include <pthread.h>
18#endif
19
20namespace fml {
21
22#if FML_THREAD_LOCAL_PTHREADS
23
24#define FML_THREAD_LOCAL static
25
26namespace internal {
27
28class ThreadLocalPointer {
29 public:
30 explicit ThreadLocalPointer(void (*destroy)(void*));
31 ~ThreadLocalPointer();
32
33 void* get() const;
34 void* swap(void* ptr);
35
36 private:
37 pthread_key_t key_;
38
39 FML_DISALLOW_COPY_AND_ASSIGN(ThreadLocalPointer);
40};
41
42} // namespace internal
43
44template <typename T>
45class ThreadLocalUniquePtr {
46 public:
47 ThreadLocalUniquePtr() : ptr_(destroy) {}
48
49 T* get() const { return reinterpret_cast<T*>(ptr_.get()); }
50 void reset(T* ptr) { destroy(ptr: ptr_.swap(ptr)); }
51
52 private:
53 static void destroy(void* ptr) { delete reinterpret_cast<T*>(ptr); }
54
55 internal::ThreadLocalPointer ptr_;
56
57 FML_DISALLOW_COPY_AND_ASSIGN(ThreadLocalUniquePtr);
58};
59
60#else // FML_THREAD_LOCAL_PTHREADS
61
62#define FML_THREAD_LOCAL static thread_local
63
64template <typename T>
65class ThreadLocalUniquePtr {
66 public:
67 ThreadLocalUniquePtr() = default;
68
69 T* get() const { return ptr_.get(); }
70 void reset(T* ptr) { ptr_.reset(ptr); }
71
72 private:
73 std::unique_ptr<T> ptr_;
74
75 FML_DISALLOW_COPY_AND_ASSIGN(ThreadLocalUniquePtr);
76};
77
78#endif // FML_THREAD_LOCAL_PTHREADS
79
80#ifndef FML_THREAD_LOCAL
81
82#error Thread local storage unavailable on the platform.
83
84#endif // FML_THREAD_LOCAL
85
86} // namespace fml
87
88#endif // FLUTTER_FML_THREAD_LOCAL_H_
89

source code of flutter_engine/flutter/fml/thread_local.h