1// Copyright (c) 2012 The Chromium 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 BASE_THREADING_THREAD_LOCAL_STORAGE_H_
6#define BASE_THREADING_THREAD_LOCAL_STORAGE_H_
7
8#include "base/atomicops.h"
9#include "base/base_export.h"
10#include "base/macros.h"
11#include "build/build_config.h"
12
13#if defined(OS_WIN)
14#include <windows.h>
15#elif defined(OS_POSIX)
16#include <pthread.h>
17#endif
18
19namespace base {
20
21namespace internal {
22
23// WARNING: You should *NOT* be using this class directly.
24// PlatformThreadLocalStorage is low-level abstraction to the OS's TLS
25// interface, you should instead be using ThreadLocalStorage::StaticSlot/Slot.
26class BASE_EXPORT PlatformThreadLocalStorage {
27 public:
28
29#if defined(OS_WIN)
30  typedef unsigned long TLSKey;
31  enum : unsigned { TLS_KEY_OUT_OF_INDEXES = TLS_OUT_OF_INDEXES };
32#elif defined(OS_POSIX)
33  typedef pthread_key_t TLSKey;
34  // The following is a "reserved key" which is used in our generic Chromium
35  // ThreadLocalStorage implementation.  We expect that an OS will not return
36  // such a key, but if it is returned (i.e., the OS tries to allocate it) we
37  // will just request another key.
38  enum { TLS_KEY_OUT_OF_INDEXES = 0x7FFFFFFF };
39#endif
40
41  // The following methods need to be supported on each OS platform, so that
42  // the Chromium ThreadLocalStore functionality can be constructed.
43  // Chromium will use these methods to acquire a single OS slot, and then use
44  // that to support a much larger number of Chromium slots (independent of the
45  // OS restrictions).
46  // The following returns true if it successfully is able to return an OS
47  // key in |key|.
48  static bool AllocTLS(TLSKey* key);
49  // Note: FreeTLS() doesn't have to be called, it is fine with this leak, OS
50  // might not reuse released slot, you might just reset the TLS value with
51  // SetTLSValue().
52  static void FreeTLS(TLSKey key);
53  static void SetTLSValue(TLSKey key, void* value);
54  static void* GetTLSValue(TLSKey key);
55
56  // Each platform (OS implementation) is required to call this method on each
57  // terminating thread when the thread is about to terminate.  This method
58  // will then call all registered destructors for slots in Chromium
59  // ThreadLocalStorage, until there are no slot values remaining as having
60  // been set on this thread.
61  // Destructors may end up being called multiple times on a terminating
62  // thread, as other destructors may re-set slots that were previously
63  // destroyed.
64#if defined(OS_WIN)
65  // Since Windows which doesn't support TLS destructor, the implementation
66  // should use GetTLSValue() to retrieve the value of TLS slot.
67  static void OnThreadExit();
68#elif defined(OS_POSIX)
69  // |Value| is the data stored in TLS slot, The implementation can't use
70  // GetTLSValue() to retrieve the value of slot as it has already been reset
71  // in Posix.
72  static void OnThreadExit(void* value);
73#endif
74};
75
76}  // namespace internal
77
78// Wrapper for thread local storage.  This class doesn't do much except provide
79// an API for portability.
80class BASE_EXPORT ThreadLocalStorage {
81 public:
82
83  // Prototype for the TLS destructor function, which can be optionally used to
84  // cleanup thread local storage on thread exit.  'value' is the data that is
85  // stored in thread local storage.
86  typedef void (*TLSDestructorFunc)(void* value);
87
88  // StaticSlot uses its own struct initializer-list style static
89  // initialization, as base's LINKER_INITIALIZED requires a constructor and on
90  // some compilers (notably gcc 4.4) this still ends up needing runtime
91  // initialization.
92  #define TLS_INITIALIZER {false, 0}
93
94  // A key representing one value stored in TLS.
95  // Initialize like
96  //   ThreadLocalStorage::StaticSlot my_slot = TLS_INITIALIZER;
97  // If you're not using a static variable, use the convenience class
98  // ThreadLocalStorage::Slot (below) instead.
99  struct BASE_EXPORT StaticSlot {
100    // Set up the TLS slot.  Called by the constructor.
101    // 'destructor' is a pointer to a function to perform per-thread cleanup of
102    // this object.  If set to NULL, no cleanup is done for this TLS slot.
103    void Initialize(TLSDestructorFunc destructor);
104
105    // Free a previously allocated TLS 'slot'.
106    // If a destructor was set for this slot, removes
107    // the destructor so that remaining threads exiting
108    // will not free data.
109    void Free();
110
111    // Get the thread-local value stored in slot 'slot'.
112    // Values are guaranteed to initially be zero.
113    void* Get() const;
114
115    // Set the thread-local value stored in slot 'slot' to
116    // value 'value'.
117    void Set(void* value);
118
119    bool initialized() const {
120      return base::subtle::Acquire_Load(&initialized_) != 0;
121    }
122
123    // The internals of this struct should be considered private.
124    base::subtle::Atomic32 initialized_;
125    int slot_;
126  };
127
128  // A convenience wrapper around StaticSlot with a constructor. Can be used
129  // as a member variable.
130  class BASE_EXPORT Slot : public StaticSlot {
131   public:
132    // Calls StaticSlot::Initialize().
133    explicit Slot(TLSDestructorFunc destructor = NULL);
134
135   private:
136    using StaticSlot::initialized_;
137    using StaticSlot::slot_;
138
139    DISALLOW_COPY_AND_ASSIGN(Slot);
140  };
141
142 private:
143  DISALLOW_COPY_AND_ASSIGN(ThreadLocalStorage);
144};
145
146}  // namespace base
147
148#endif  // BASE_THREADING_THREAD_LOCAL_STORAGE_H_
149