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 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE file.
7 #ifndef BASE_THREAD_LOCAL_STORAGE_H_
8 #define BASE_THREAD_LOCAL_STORAGE_H_
10 #include "base/basictypes.h"
16 // Wrapper for thread local storage. This class doesn't do much except provide
17 // an API for portability.
18 class ThreadLocalStorage
{
20 // Prototype for the TLS destructor function, which can be optionally used to
21 // cleanup thread local storage on thread exit. 'value' is the data that is
22 // stored in thread local storage.
23 typedef void (*TLSDestructorFunc
)(void* value
);
25 // A key representing one value stored in TLS.
28 explicit Slot(TLSDestructorFunc destructor
= NULL
);
30 // This constructor should be used for statics.
31 // It returns an uninitialized Slot.
32 explicit Slot(base::LinkerInitialized x
) {}
34 // Set up the TLS slot. Called by the constructor.
35 // 'destructor' is a pointer to a function to perform per-thread cleanup of
36 // this object. If set to NULL, no cleanup is done for this TLS slot.
37 // Returns false on error.
38 bool Initialize(TLSDestructorFunc destructor
);
40 // Free a previously allocated TLS 'slot'.
41 // If a destructor was set for this slot, removes
42 // the destructor so that remaining threads exiting
43 // will not free data.
46 // Get the thread-local value stored in slot 'slot'.
47 // Values are guaranteed to initially be zero.
50 // Set the thread-local value stored in slot 'slot' to
52 void Set(void* value
);
54 bool initialized() const { return initialized_
; }
57 // The internals of this struct should be considered private.
65 DISALLOW_COPY_AND_ASSIGN(Slot
);
69 // Function called when on thread exit to call TLS
70 // destructor functions. This function is used internally.
71 static void ThreadExit();
74 // Function to lazily initialize our thread local storage.
75 static void** Initialize();
78 // The maximum number of 'slots' in our thread local storage stack.
79 // For now, this is fixed. We could either increase statically, or
80 // we could make it dynamic in the future.
81 static const int kThreadLocalStorageSize
= 64;
85 static TLSDestructorFunc tls_destructors_
[kThreadLocalStorageSize
];
88 DISALLOW_COPY_AND_ASSIGN(ThreadLocalStorage
);
91 // Temporary backwards-compatible name.
92 // TODO(evanm): replace all usage of TLSSlot.
93 typedef ThreadLocalStorage::Slot TLSSlot
;
95 #endif // BASE_THREAD_LOCAL_STORAGE_H_