1// Copyright (c) 2014, Jason Choy <jjwchoy@gmail.com>
2// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
3// Licensed under the MIT License:
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21// THE SOFTWARE.
22
23#pragma once
24
25#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
26#pragma GCC system_header
27#endif
28// This file declares a macro `KJ_THREADLOCAL_PTR` for declaring thread-local pointer-typed
29// variables. Use like:
30// KJ_THREADLOCAL_PTR(MyType) foo = nullptr;
31// This is equivalent to:
32// thread_local MyType* foo = nullptr;
33// This can only be used at the global scope.
34//
35// AVOID USING THIS. Use of thread-locals is discouraged because they often have many of the same
36// properties as singletons: http://www.object-oriented-security.org/lets-argue/singletons
37//
38// Also, thread-locals tend to be hostile to event-driven code, which can be particularly
39// surprising when using fibers (all fibers in the same thread will share the same threadlocals,
40// even though they do not share a stack).
41//
42// That said, thread-locals are sometimes needed for runtime logistics in the KJ framework. For
43// example, the current exception callback and current EventLoop are stored as thread-local
44// pointers. Since KJ only ever needs to store pointers, not values, we avoid the question of
45// whether these values' destructors need to be run, and we avoid the need for heap allocation.
46
47#include "common.h"
48
49#if !defined(KJ_USE_PTHREAD_THREADLOCAL) && defined(__APPLE__)
50#include "TargetConditionals.h"
51#if TARGET_OS_IPHONE
52// iOS apparently does not support __thread (nor C++11 thread_local).
53#define KJ_USE_PTHREAD_TLS 1
54#endif
55#endif
56
57#if KJ_USE_PTHREAD_TLS
58#include <pthread.h>
59#endif
60
61namespace kj {
62
63#if KJ_USE_PTHREAD_TLS
64// If __thread is unavailable, we'll fall back to pthreads.
65
66#define KJ_THREADLOCAL_PTR(type) \
67 namespace { struct KJ_UNIQUE_NAME(_kj_TlpTag); } \
68 static ::kj::_::ThreadLocalPtr< type, KJ_UNIQUE_NAME(_kj_TlpTag)>
69// Hack: In order to ensure each thread-local results in a unique template instance, we declare
70// a one-off dummy type to use as the second type parameter.
71
72namespace _ { // private
73
74template <typename T, typename>
75class ThreadLocalPtr {
76 // Hacky type to emulate __thread T*. We need a separate instance of the ThreadLocalPtr template
77 // for every thread-local variable, because we don't want to require a global constructor, and in
78 // order to initialize the TLS on first use we need to use a local static variable (in getKey()).
79 // Each template instance will get a separate such local static variable, fulfilling our need.
80
81public:
82 ThreadLocalPtr() = default;
83 constexpr ThreadLocalPtr(decltype(nullptr)) {}
84 // Allow initialization to nullptr without a global constructor.
85
86 inline ThreadLocalPtr& operator=(T* val) {
87 pthread_setspecific(getKey(), val);
88 return *this;
89 }
90
91 inline operator T*() const {
92 return get();
93 }
94
95 inline T& operator*() const {
96 return *get();
97 }
98
99 inline T* operator->() const {
100 return get();
101 }
102
103private:
104 inline T* get() const {
105 return reinterpret_cast<T*>(pthread_getspecific(getKey()));
106 }
107
108 inline static pthread_key_t getKey() {
109 static pthread_key_t key = createKey();
110 return key;
111 }
112
113 static pthread_key_t createKey() {
114 pthread_key_t key;
115 pthread_key_create(&key, 0);
116 return key;
117 }
118};
119
120} // namespace _ (private)
121
122#elif __GNUC__
123
124#define KJ_THREADLOCAL_PTR(type) static __thread type*
125// GCC's __thread is lighter-weight than thread_local and is good enough for our purposes.
126
127#else
128
129#define KJ_THREADLOCAL_PTR(type) static thread_local type*
130
131#endif // KJ_USE_PTHREAD_TLS
132
133} // namespace kj
134