Home | History | Annotate | Download | only in wtf
      1 /*
      2  * Copyright (C) 2008 Apple Inc. All rights reserved.
      3  * Copyright (C) 2009 Jian Li <jianli (at) chromium.org>
      4  * Copyright (C) 2012 Patrick Gansterer <paroga (at) paroga.com>
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  *
     10  * 1.  Redistributions of source code must retain the above copyright
     11  *     notice, this list of conditions and the following disclaimer.
     12  * 2.  Redistributions in binary form must reproduce the above copyright
     13  *     notice, this list of conditions and the following disclaimer in the
     14  *     documentation and/or other materials provided with the distribution.
     15  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
     16  *     its contributors may be used to endorse or promote products derived
     17  *     from this software without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
     20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
     23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 /* Thread local storage is implemented by using either pthread API or Windows
     32  * native API. There is subtle semantic discrepancy for the cleanup function
     33  * implementation as noted below:
     34  *   @ In pthread implementation, the destructor function will be called
     35  *     repeatedly if there is still non-NULL value associated with the function.
     36  *   @ In Windows native implementation, the destructor function will be called
     37  *     only once.
     38  * This semantic discrepancy does not impose any problem because nowhere in
     39  * WebKit the repeated call bahavior is utilized.
     40  */
     41 
     42 #ifndef WTF_ThreadSpecific_h
     43 #define WTF_ThreadSpecific_h
     44 
     45 #include "wtf/Noncopyable.h"
     46 #include "wtf/StdLibExtras.h"
     47 #include "wtf/WTFExport.h"
     48 
     49 #if USE(PTHREADS)
     50 #include <pthread.h>
     51 #elif OS(WINDOWS)
     52 #include <windows.h>
     53 #endif
     54 
     55 namespace WTF {
     56 
     57 #if OS(WINDOWS)
     58 // ThreadSpecificThreadExit should be called each time when a thread is detached.
     59 // This is done automatically for threads created with WTF::createThread.
     60 WTF_EXPORT void ThreadSpecificThreadExit();
     61 #endif
     62 
     63 template<typename T> class ThreadSpecific {
     64     WTF_MAKE_NONCOPYABLE(ThreadSpecific);
     65 public:
     66     ThreadSpecific();
     67     bool isSet(); // Useful as a fast check to see if this thread has set this value.
     68     T* operator->();
     69     operator T*();
     70     T& operator*();
     71 
     72 private:
     73 #if OS(WINDOWS)
     74     WTF_EXPORT friend void ThreadSpecificThreadExit();
     75 #endif
     76 
     77     // Not implemented. It's technically possible to destroy a thread specific key, but one would need
     78     // to make sure that all values have been destroyed already (usually, that all threads that used it
     79     // have exited). It's unlikely that any user of this call will be in that situation - and having
     80     // a destructor defined can be confusing, given that it has such strong pre-requisites to work correctly.
     81     ~ThreadSpecific();
     82 
     83     T* get();
     84     void set(T*);
     85     void static destroy(void* ptr);
     86 
     87     struct Data {
     88         WTF_MAKE_NONCOPYABLE(Data);
     89     public:
     90         Data(T* value, ThreadSpecific<T>* owner) : value(value), owner(owner) {}
     91 
     92         T* value;
     93         ThreadSpecific<T>* owner;
     94 #if OS(WINDOWS)
     95         void (*destructor)(void*);
     96 #endif
     97     };
     98 
     99 #if USE(PTHREADS)
    100     pthread_key_t m_key;
    101 #elif OS(WINDOWS)
    102     int m_index;
    103 #endif
    104 };
    105 
    106 #if USE(PTHREADS)
    107 
    108 typedef pthread_key_t ThreadSpecificKey;
    109 
    110 inline void threadSpecificKeyCreate(ThreadSpecificKey* key, void (*destructor)(void *))
    111 {
    112     int error = pthread_key_create(key, destructor);
    113     if (error)
    114         CRASH();
    115 }
    116 
    117 inline void threadSpecificKeyDelete(ThreadSpecificKey key)
    118 {
    119     int error = pthread_key_delete(key);
    120     if (error)
    121         CRASH();
    122 }
    123 
    124 inline void threadSpecificSet(ThreadSpecificKey key, void* value)
    125 {
    126     pthread_setspecific(key, value);
    127 }
    128 
    129 inline void* threadSpecificGet(ThreadSpecificKey key)
    130 {
    131     return pthread_getspecific(key);
    132 }
    133 
    134 template<typename T>
    135 inline ThreadSpecific<T>::ThreadSpecific()
    136 {
    137     int error = pthread_key_create(&m_key, destroy);
    138     if (error)
    139         CRASH();
    140 }
    141 
    142 template<typename T>
    143 inline T* ThreadSpecific<T>::get()
    144 {
    145     Data* data = static_cast<Data*>(pthread_getspecific(m_key));
    146     return data ? data->value : 0;
    147 }
    148 
    149 template<typename T>
    150 inline void ThreadSpecific<T>::set(T* ptr)
    151 {
    152     ASSERT(!get());
    153     pthread_setspecific(m_key, new Data(ptr, this));
    154 }
    155 
    156 #elif OS(WINDOWS)
    157 
    158 // TLS_OUT_OF_INDEXES is not defined on WinCE.
    159 #ifndef TLS_OUT_OF_INDEXES
    160 #define TLS_OUT_OF_INDEXES 0xffffffff
    161 #endif
    162 
    163 // The maximum number of TLS keys that can be created. For simplification, we assume that:
    164 // 1) Once the instance of ThreadSpecific<> is created, it will not be destructed until the program dies.
    165 // 2) We do not need to hold many instances of ThreadSpecific<> data. This fixed number should be far enough.
    166 const int kMaxTlsKeySize = 256;
    167 
    168 WTF_EXPORT long& tlsKeyCount();
    169 WTF_EXPORT DWORD* tlsKeys();
    170 
    171 class PlatformThreadSpecificKey;
    172 typedef PlatformThreadSpecificKey* ThreadSpecificKey;
    173 
    174 WTF_EXPORT void threadSpecificKeyCreate(ThreadSpecificKey*, void (*)(void *));
    175 WTF_EXPORT void threadSpecificKeyDelete(ThreadSpecificKey);
    176 WTF_EXPORT void threadSpecificSet(ThreadSpecificKey, void*);
    177 WTF_EXPORT void* threadSpecificGet(ThreadSpecificKey);
    178 
    179 template<typename T>
    180 inline ThreadSpecific<T>::ThreadSpecific()
    181     : m_index(-1)
    182 {
    183     DWORD tlsKey = TlsAlloc();
    184     if (tlsKey == TLS_OUT_OF_INDEXES)
    185         CRASH();
    186 
    187     m_index = InterlockedIncrement(&tlsKeyCount()) - 1;
    188     if (m_index >= kMaxTlsKeySize)
    189         CRASH();
    190     tlsKeys()[m_index] = tlsKey;
    191 }
    192 
    193 template<typename T>
    194 inline ThreadSpecific<T>::~ThreadSpecific()
    195 {
    196     // Does not invoke destructor functions. They will be called from ThreadSpecificThreadExit when the thread is detached.
    197     TlsFree(tlsKeys()[m_index]);
    198 }
    199 
    200 template<typename T>
    201 inline T* ThreadSpecific<T>::get()
    202 {
    203     Data* data = static_cast<Data*>(TlsGetValue(tlsKeys()[m_index]));
    204     return data ? data->value : 0;
    205 }
    206 
    207 template<typename T>
    208 inline void ThreadSpecific<T>::set(T* ptr)
    209 {
    210     ASSERT(!get());
    211     Data* data = new Data(ptr, this);
    212     data->destructor = &ThreadSpecific<T>::destroy;
    213     TlsSetValue(tlsKeys()[m_index], data);
    214 }
    215 
    216 #else
    217 #error ThreadSpecific is not implemented for this platform.
    218 #endif
    219 
    220 template<typename T>
    221 inline void ThreadSpecific<T>::destroy(void* ptr)
    222 {
    223     Data* data = static_cast<Data*>(ptr);
    224 
    225 #if USE(PTHREADS)
    226     // We want get() to keep working while data destructor works, because it can be called indirectly by the destructor.
    227     // Some pthreads implementations zero out the pointer before calling destroy(), so we temporarily reset it.
    228     pthread_setspecific(data->owner->m_key, ptr);
    229 #endif
    230 
    231     data->value->~T();
    232     fastFree(data->value);
    233 
    234 #if USE(PTHREADS)
    235     pthread_setspecific(data->owner->m_key, 0);
    236 #elif OS(WINDOWS)
    237     TlsSetValue(tlsKeys()[data->owner->m_index], 0);
    238 #else
    239 #error ThreadSpecific is not implemented for this platform.
    240 #endif
    241 
    242     delete data;
    243 }
    244 
    245 template<typename T>
    246 inline bool ThreadSpecific<T>::isSet()
    247 {
    248     return !!get();
    249 }
    250 
    251 template<typename T>
    252 inline ThreadSpecific<T>::operator T*()
    253 {
    254     T* ptr = static_cast<T*>(get());
    255     if (!ptr) {
    256         // Set up thread-specific value's memory pointer before invoking constructor, in case any function it calls
    257         // needs to access the value, to avoid recursion.
    258         ptr = static_cast<T*>(fastZeroedMalloc(sizeof(T)));
    259         set(ptr);
    260         new (NotNull, ptr) T;
    261     }
    262     return ptr;
    263 }
    264 
    265 template<typename T>
    266 inline T* ThreadSpecific<T>::operator->()
    267 {
    268     return operator T*();
    269 }
    270 
    271 template<typename T>
    272 inline T& ThreadSpecific<T>::operator*()
    273 {
    274     return *operator T*();
    275 }
    276 
    277 } // namespace WTF
    278 
    279 #endif // WTF_ThreadSpecific_h
    280