1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
4 * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 /* Cross-platform lightweight thread local data wrappers. */
12 // This file will get included in any file that wants to add a profiler mark.
13 // In order to not bring <windows.h> together we could include windef.h and
14 // winbase.h which are sufficient to get the prototypes for the Tls* functions.
15 // # include <windef.h>
16 // # include <winbase.h>
17 // Unfortunately, even including these headers causes us to add a bunch of ugly
18 // stuff to our namespace e.g #define CreateEvent CreateEventW
20 __declspec(dllimport
) void * __stdcall
TlsGetValue(unsigned long);
21 __declspec(dllimport
) int __stdcall
TlsSetValue(unsigned long, void *);
22 __declspec(dllimport
) unsigned long __stdcall
TlsAlloc();
29 #include "mozilla/Assertions.h"
30 #include "mozilla/Attributes.h"
34 // sig_safe_t denotes an atomic type which can be read or stored in a single
35 // instruction. This means that data of this type is safe to be manipulated
36 // from a signal handler, or other similar asynchronous execution contexts.
38 typedef unsigned long sig_safe_t
;
40 typedef sig_atomic_t sig_safe_t
;
44 * Thread Local Storage helpers.
48 * Only static-storage-duration (e.g. global variables, or static class members)
49 * objects of this class should be instantiated. This class relies on
50 * zero-initialization, which is implicit for static-storage-duration objects.
51 * It doesn't have a custom default constructor, to avoid static initializers.
55 * // Create a TLS item
56 * mozilla::ThreadLocal<int> tlsKey;
57 * if (!tlsKey.init()) {
58 * // deal with the error
61 * // Set the TLS value
64 * // Get the TLS value
65 * int value = tlsKey.get();
71 typedef unsigned long key_t
;
73 typedef pthread_key_t key_t
;
82 MOZ_WARN_UNUSED_RESULT
inline bool init();
86 inline bool set(const T value
);
88 bool initialized() const {
99 ThreadLocal
<T
>::init()
101 MOZ_STATIC_ASSERT(sizeof(T
) <= sizeof(void *),
102 "mozilla::ThreadLocal can't be used for types larger than "
104 MOZ_ASSERT(!initialized());
107 inited
= key
!= 0xFFFFFFFFUL
; // TLS_OUT_OF_INDEXES
109 inited
= !pthread_key_create(&key
, NULL
);
116 ThreadLocal
<T
>::get() const
118 MOZ_ASSERT(initialized());
121 h
.ptr
= TlsGetValue(key
);
123 h
.ptr
= pthread_getspecific(key
);
130 ThreadLocal
<T
>::set(const T value
)
132 MOZ_ASSERT(initialized());
136 return TlsSetValue(key
, h
.ptr
);
138 return !pthread_setspecific(key
, h
.ptr
);
142 } // namespace mozilla
144 #endif // mozilla_TLS_h_