1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Cross-platform lightweight thread local data wrappers. */
9 #ifndef mozilla_ThreadLocal_h
10 #define mozilla_ThreadLocal_h
13 // This file will get included in any file that wants to add a profiler mark.
14 // In order to not bring <windows.h> together we could include windef.h and
15 // winbase.h which are sufficient to get the prototypes for the Tls* functions.
16 // # include <windef.h>
17 // # include <winbase.h>
18 // Unfortunately, even including these headers causes us to add a bunch of ugly
19 // stuff to our namespace e.g #define CreateEvent CreateEventW
21 __declspec(dllimport
) void* __stdcall
TlsGetValue(unsigned long);
22 __declspec(dllimport
) int __stdcall
TlsSetValue(unsigned long, void*);
23 __declspec(dllimport
) unsigned long __stdcall
TlsAlloc();
30 #include "mozilla/Assertions.h"
31 #include "mozilla/Attributes.h"
32 #include "mozilla/NullPtr.h"
36 // sig_safe_t denotes an atomic type which can be read or stored in a single
37 // instruction. This means that data of this type is safe to be manipulated
38 // from a signal handler, or other similar asynchronous execution contexts.
40 typedef unsigned long sig_safe_t
;
42 typedef sig_atomic_t sig_safe_t
;
46 * Thread Local Storage helpers.
50 * Only static-storage-duration (e.g. global variables, or static class members)
51 * objects of this class should be instantiated. This class relies on
52 * zero-initialization, which is implicit for static-storage-duration objects.
53 * It doesn't have a custom default constructor, to avoid static initializers.
57 * // Create a TLS item
58 * mozilla::ThreadLocal<int> tlsKey;
59 * if (!tlsKey.init()) {
60 * // deal with the error
63 * // Set the TLS value
66 * // Get the TLS value
67 * int value = tlsKey.get();
73 typedef unsigned long key_t
;
75 typedef pthread_key_t key_t
;
84 MOZ_WARN_UNUSED_RESULT
inline bool init();
88 inline void set(const T value
);
90 bool initialized() const {
101 ThreadLocal
<T
>::init()
103 static_assert(sizeof(T
) <= sizeof(void*),
104 "mozilla::ThreadLocal can't be used for types larger than "
106 MOZ_ASSERT(!initialized());
109 inited
= key
!= 0xFFFFFFFFUL
; // TLS_OUT_OF_INDEXES
111 inited
= !pthread_key_create(&key
, nullptr);
118 ThreadLocal
<T
>::get() const
120 MOZ_ASSERT(initialized());
123 h
.ptr
= TlsGetValue(key
);
125 h
.ptr
= pthread_getspecific(key
);
132 ThreadLocal
<T
>::set(const T value
)
134 MOZ_ASSERT(initialized());
139 succeeded
= TlsSetValue(key
, h
.ptr
);
141 succeeded
= !pthread_setspecific(key
, h
.ptr
);
147 } // namespace mozilla
149 #endif /* mozilla_ThreadLocal_h */