1 // ThreadLocal.cpp 2 3 #include <new> 4 5 #include <OS.h> 6 7 #include "HashMap.h" 8 #include "ThreadLocal.h" 9 10 // ThreadLocalFreeHandler 11 12 // constructor 13 ThreadLocalFreeHandler::ThreadLocalFreeHandler() 14 { 15 } 16 17 // destructor 18 ThreadLocalFreeHandler::~ThreadLocalFreeHandler() 19 { 20 } 21 22 23 // ThreadLocal 24 25 // ThreadLocalMap 26 struct ThreadLocal::ThreadLocalMap 27 : public SynchronizedHashMap<HashKey32<thread_id>, void*> { 28 }; 29 30 // constructor 31 ThreadLocal::ThreadLocal(ThreadLocalFreeHandler* freeHandler) 32 : fMap(NULL), 33 fFreeHandler(freeHandler) 34 { 35 fMap = new(std::nothrow) ThreadLocalMap; 36 } 37 38 // destructor 39 ThreadLocal::~ThreadLocal() 40 { 41 delete fMap; 42 } 43 44 // Set 45 status_t 46 ThreadLocal::Set(void* data) 47 { 48 if (!fMap) 49 return B_NO_MEMORY; 50 thread_id thread = find_thread(NULL); 51 fMap->Lock(); 52 // free old data, if any 53 if (fFreeHandler &&fMap->ContainsKey(thread)) 54 fFreeHandler->Free(fMap->Get(thread)); 55 // put the new data 56 status_t error = fMap->Put(thread, data); 57 fMap->Unlock(); 58 return error; 59 } 60 61 // Unset 62 void 63 ThreadLocal::Unset() 64 { 65 if (!fMap) 66 return; 67 thread_id thread = find_thread(NULL); 68 fMap->Lock(); 69 if (fFreeHandler) { 70 if (fMap->ContainsKey(thread)) 71 fFreeHandler->Free(fMap->Remove(thread)); 72 } else 73 fMap->Remove(thread); 74 fMap->Unlock(); 75 } 76 77 // Get 78 void* 79 ThreadLocal::Get() const 80 { 81 if (!fMap) 82 return NULL; 83 return fMap->Get(find_thread(NULL)); 84 } 85 86