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.
5 #ifndef BASE_THREADING_THREAD_LOCAL_STORAGE_H_
6 #define BASE_THREADING_THREAD_LOCAL_STORAGE_H_
8 #include "base/base_export.h"
9 #include "base/basictypes.h"
17 // Wrapper for thread local storage. This class doesn't do much except provide
18 // an API for portability.
19 class BASE_EXPORT ThreadLocalStorage
{
22 // Prototype for the TLS destructor function, which can be optionally used to
23 // cleanup thread local storage on thread exit. 'value' is the data that is
24 // stored in thread local storage.
25 typedef void (*TLSDestructorFunc
)(void* value
);
27 // StaticSlot uses its own struct initializer-list style static
28 // initialization, as base's LINKER_INITIALIZED requires a constructor and on
29 // some compilers (notably gcc 4.4) this still ends up needing runtime
31 #define TLS_INITIALIZER {0}
33 // A key representing one value stored in TLS.
35 // ThreadLocalStorage::StaticSlot my_slot = TLS_INITIALIZER;
36 // If you're not using a static variable, use the convenience class
37 // ThreadLocalStorage::Slot (below) instead.
38 struct BASE_EXPORT StaticSlot
{
39 // Set up the TLS slot. Called by the constructor.
40 // 'destructor' is a pointer to a function to perform per-thread cleanup of
41 // this object. If set to NULL, no cleanup is done for this TLS slot.
42 // Returns false on error.
43 bool Initialize(TLSDestructorFunc destructor
);
45 // Free a previously allocated TLS 'slot'.
46 // If a destructor was set for this slot, removes
47 // the destructor so that remaining threads exiting
48 // will not free data.
51 // Get the thread-local value stored in slot 'slot'.
52 // Values are guaranteed to initially be zero.
55 // Set the thread-local value stored in slot 'slot' to
57 void Set(void* value
);
59 bool initialized() const { return initialized_
; }
61 // The internals of this struct should be considered private.
65 #elif defined(OS_POSIX)
71 // A convenience wrapper around StaticSlot with a constructor. Can be used
72 // as a member variable.
73 class BASE_EXPORT Slot
: public StaticSlot
{
75 // Calls StaticSlot::Initialize().
76 explicit Slot(TLSDestructorFunc destructor
= NULL
);
79 using StaticSlot::initialized_
;
81 using StaticSlot::slot_
;
82 #elif defined(OS_POSIX)
83 using StaticSlot::key_
;
85 DISALLOW_COPY_AND_ASSIGN(Slot
);
88 DISALLOW_COPY_AND_ASSIGN(ThreadLocalStorage
);
93 #endif // BASE_THREADING_THREAD_LOCAL_STORAGE_H_