18 #ifndef ION_BASE_THREADLOCALOBJECT_H_
19 #define ION_BASE_THREADLOCALOBJECT_H_
82 allocator_(allocator) {}
86 DestroyAllInstances();
101 return static_cast<T*
>(ptr);
103 return CreateAndStoreInstance();
109 template <
typename InstanceType,
bool IsAllocatable = false>
110 struct AllocationHelper {
111 static InstanceType* Allocate(
const AllocatorPtr& allocator) {
112 return new InstanceType();
115 template <
typename InstanceType>
struct AllocationHelper<InstanceType, true> {
116 static InstanceType* Allocate(
const AllocatorPtr& allocator) {
117 return new(allocator) InstanceType();
123 T* CreateAndStoreInstance() {
125 if (key_ != port::kInvalidThreadLocalStorageKey) {
126 instance = AllocateInstance(allocator_);
129 instances_.push_back(instance);
138 return HelperType::Allocate(allocator);
142 void DestroyAllInstances() {
144 const size_t num_instances = instances_.size();
145 for (
size_t i = 0; i < num_instances; ++i)
146 delete instances_[i];
155 std::vector<T*> instances_;
163 #endif // ION_BASE_THREADLOCALOBJECT_H_
ThreadLocalStorageKey CreateThreadLocalStorageKey()
Thread-local storage functions.
GenericLockGuard< port::Mutex > LockGuard
Convenient typedefs for ion::port::Mutex.
ThreadLocalObject(const AllocatorPtr &allocator)
This constructor uses the given Allocator to construct T instances.
ThreadLocalObject()
The default constructor will use global operator new() to construct T instances.
SharedPtr< Allocator > AllocatorPtr
bool SetThreadLocalStorage(ThreadLocalStorageKey key, void *ptr)
Associates ptr with the thread-local storage area indicated by key.
pthread_key_t ThreadLocalStorageKey
Defines a type that is used to access thread-local storage.
T * Get()
Returns a T instance for the current thread, creating it first if necessary.
const port::ThreadLocalStorageKey & GetKey() const
Returns the ThreadLocalStorageKey created by the instance.
void * GetThreadLocalStorage(ThreadLocalStorageKey key)
Returns the pointer to the thread-local storage area indicated by key.
bool DeleteThreadLocalStorageKey(ThreadLocalStorageKey key)
Deletes a key returned by CreateThreadLocalStorageKey().
This templated class makes it easy to create an instance of an object in thread-local storage...