00001 /* 00002 * MSThreads.hh 00003 * 00004 * Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved. 00005 * Copyright 2002, Bastiaan Bakker. All rights reserved. 00006 * 00007 * See the COPYING file for the terms of usage and distribution. 00008 */ 00009 00010 #ifndef _LOG4CPP_THREADING_MSTHREADS_HH 00011 #define _LOG4CPP_THREADING_MSTHREADS_HH 00012 00013 #include <string> 00014 00015 // deal with ERROR #define 00016 // N.B. This #includes windows.h with NOGDI and WIN32_LEAN_AND_MEAN #defined. 00017 // If this is not what the user wants, #include windows.h before this file. 00018 #ifndef _WINDOWS_ 00019 # ifndef NOGDI 00020 # define NOGDI // this will circumvent the ERROR #define in windows.h 00021 # define LOG4CPP_UNDEFINE_NOGDI 00022 # endif 00023 00024 # ifndef WIN32_LEAN_AND_MEAN 00025 # define WIN32_LEAN_AND_MEAN 00026 # define LOG4CPP_UNDEFINE_WIN32_LEAN_AND_MEAN 00027 # endif 00028 00029 # include <windows.h> 00030 00031 # ifdef LOG4CPP_UNDEFINE_NOGDI 00032 # undef NOGDI 00033 # endif 00034 00035 # ifdef LOG4CPP_UNDEFINE_WIN32_LEAN_AND_MEAN 00036 # undef WIN32_LEAN_AND_MEAN 00037 # endif 00038 00039 #endif // done dealing with ERROR #define 00040 00041 LOG4CPP_NS_BEGIN 00042 namespace threading { 00048 std::string getThreadId(); 00049 00053 class LOG4CPP_EXPORT MSMutex { 00054 public: 00055 MSMutex() { InitializeCriticalSection(&_criticalSection); } 00056 ~MSMutex() { DeleteCriticalSection(&_criticalSection); } 00057 inline LPCRITICAL_SECTION getCriticalSection() { 00058 return &_criticalSection; 00059 } 00060 00061 private: 00062 MSMutex(const MSMutex& other); 00063 CRITICAL_SECTION _criticalSection; 00064 }; 00065 00069 typedef MSMutex Mutex; 00070 00075 class MSScopedLock { 00076 public: 00077 MSScopedLock(MSMutex& mutex) { 00078 _criticalSection = mutex.getCriticalSection(); 00079 EnterCriticalSection(_criticalSection); 00080 } 00081 00082 ~MSScopedLock() { LeaveCriticalSection(_criticalSection); } 00083 00084 private: 00085 MSScopedLock(const MSScopedLock& other); 00086 LPCRITICAL_SECTION _criticalSection; 00087 }; 00088 00093 typedef MSScopedLock ScopedLock; 00094 00101 template<typename T> class ThreadLocalDataHolder { 00102 public: 00103 inline ThreadLocalDataHolder() : 00104 _key(TlsAlloc()) {}; 00105 00106 inline ~ThreadLocalDataHolder() { 00107 TlsFree(_key); 00108 }; 00109 00115 inline T* get() const { 00116 return (T*)TlsGetValue(_key); 00117 }; 00118 00125 inline T* operator->() const { return get(); }; 00126 00132 inline T& operator*() const { return *get(); }; 00133 00140 inline T* release() { 00141 T* result = (T*)TlsGetValue(_key); 00142 TlsSetValue(_key, NULL); 00143 return result; 00144 }; 00145 00152 inline void reset(T* p = NULL) { 00153 T* thing = (T*)TlsGetValue(_key); 00154 delete thing; 00155 TlsSetValue(_key, p); 00156 }; 00157 00158 private: 00159 DWORD _key; 00160 }; 00161 } 00162 LOG4CPP_NS_END 00163 #endif