00001 #ifndef __LDK_THREADLOCALSTORAGE_H__ 00002 #define __LDK_THREADLOCALSTORAGE_H__ 00003 00005 // Copyright (C) 2003-2006 Lorien Dunn. 00006 // 00007 // Contact: loriendunn AT users DOT sourceforge DOT net 00008 // 00009 // This software is provided 'as-is', without any express or implied warranty. 00010 // In no event will the authors be held liable for any damages arising from 00011 // the use of this software. 00012 // 00013 // Permission is granted to anyone to use this software for any purpose, 00014 // including commercial applications, and to alter it and redistribute it 00015 // freely, subject to the following restrictions: 00016 // 00017 // 1. The origin of this software must not be misrepresented; you must not 00018 // claim that you wrote the original software. If you use this software in a 00019 // product, an acknowledgment in the product documentation would be 00020 // appreciated but is not required. 00021 // 00022 // 2. Altered source versions must be plainly marked as such, and must not be 00023 // misrepresented as being the original software. 00024 // 00025 // 3. This notice may not be removed or altered from any source distribution. 00026 // 00028 00033 #include "LDK/API.h" 00034 #include "LDK/Types.h" 00035 extern "C" 00036 { 00060 00065 typedef void (*ThreadLocalDtor) (void*); 00066 00071 typedef size_t TLSKey; 00072 00080 LDK_TLS_API TLSKey threadLocalCreateKey(ThreadLocalDtor dtor=NULL); 00081 00088 LDK_TLS_API void threadLocalSet(TLSKey key, void* object); 00089 00097 LDK_TLS_API void* threadLocalGet(TLSKey key); 00098 00099 }//etxern "C" 00100 00101 template <typename T> 00102 class ThreadLocal 00103 { 00104 protected: 00105 00106 void *mPtr; 00107 TLSKey mKey; 00108 static void tlsdtor(void* self) { if(self) delete reinterpret_cast<T*>(self); } 00109 00110 public: 00111 00112 ThreadLocal() 00113 { 00114 mKey = threadLocalCreateKey(tlsdtor); 00115 } 00116 00117 T* operator->() 00118 { 00119 T* tlsd = reinterpret_cast<T*>(threadLocalGet(mKey)); 00120 if(!tlsd) 00121 { 00122 tlsd = new T(); 00123 threadLocalSet(mKey,tlsd); 00124 } 00125 return tlsd; 00126 } 00127 00128 T& operator&() 00129 { 00130 T* tlsd = reinterpret_cast<T*>(threadLocalGet(mKey)); 00131 if(!tlsd) 00132 { 00133 tlsd = new T(); 00134 threadLocalSet(mKey,tlsd); 00135 } 00136 return *tlsd; 00137 } 00138 }; 00139 00141 00142 #endif //__LDK_THREADLOCALSTORAGE_H__