Changeset 377
- Timestamp:
- 04/27/15 04:42:52 (10 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
cpp/common/threads.h
r371 r377 24 24 template<class T> class ThreadSingleton 25 25 { 26 pthread_key_t mt_key;26 pthread_key_t mt_key; 27 27 28 28 public: 29 29 30 ThreadSingleton()31 32 pthread_key_create(&mt_key,&destructor);33 30 ThreadSingleton() 31 { 32 pthread_key_create(&mt_key, &destructor); 33 } 34 34 35 ~ThreadSingleton()36 37 T* o=set(NULL);38 39 35 ~ThreadSingleton() 36 { 37 T* o = set(NULL); 38 if (o) delete o; 39 } 40 40 41 static void destructor(void* o)42 43 44 45 41 static void destructor(void* o) 42 { 43 if (o) 44 delete (T*)o; 45 } 46 46 47 T* set(T* new_o)48 49 T* o=(T*)pthread_getspecific(mt_key);50 pthread_setspecific(mt_key,new_o);51 52 47 T* set(T* new_o) 48 { 49 T* o = (T*)pthread_getspecific(mt_key); 50 pthread_setspecific(mt_key, new_o); 51 return o; 52 } 53 53 54 T* get()55 56 T* o=(T*)pthread_getspecific(mt_key);57 58 59 o=new T();60 pthread_setspecific(mt_key,o);61 62 63 54 T* get() 55 { 56 T* o = (T*)pthread_getspecific(mt_key); 57 if (!o) 58 { 59 o = new T(); 60 pthread_setspecific(mt_key, o); 61 } 62 return o; 63 } 64 64 65 T& getref() {return *get();}65 T& getref() { return *get(); } 66 66 }; 67 67 68 68 template<class T> class ThreadSingletonPtr 69 69 { 70 pthread_key_t mt_key;70 pthread_key_t mt_key; 71 71 72 72 public: 73 73 74 ThreadSingletonPtr()75 76 pthread_key_create(&mt_key,NULL);77 74 ThreadSingletonPtr() 75 { 76 pthread_key_create(&mt_key, NULL); 77 } 78 78 79 T* setptr(T* new_o)80 81 T* o=(T*)pthread_getspecific(mt_key);82 pthread_setspecific(mt_key,new_o);83 84 79 T* setptr(T* new_o) 80 { 81 T* o = (T*)pthread_getspecific(mt_key); 82 pthread_setspecific(mt_key, new_o); 83 return o; 84 } 85 85 86 T* get()87 88 89 86 T* get() 87 { 88 return (T*)pthread_getspecific(mt_key); 89 } 90 90 }; 91 91 92 92 #else //ifdef MULTITHREADED 93 94 #include <cstddef> //NULL 93 95 94 96 #define tlsGet(var) (&ThreadLocal_ ## var ## _getref()) … … 105 107 template<class T> class ThreadSingletonPtr 106 108 { 107 T *object;108 109 ThreadSingletonPtr():object(NULL) {}110 T* get() {return object;}111 T* setptr(T* o) {T* previous=object; object=o; return previous;}109 T *object; 110 public: 111 ThreadSingletonPtr():object(NULL) {} 112 T* get() {return object;} 113 T* setptr(T* o) {T* previous=object; object=o; return previous;} 112 114 }; 113 115 … … 131 133 template<class T> T* _tlsGet(T*& var) 132 134 { 133 if (!var)134 var=new T();135 return var;135 if (!var) 136 var=new T(); 137 return var; 136 138 } 137 139 138 140 template<class T> T* _tlsGetPtr(T*& var) 139 141 { 140 return var;142 return var; 141 143 } 142 144 … … 146 148 template<class T> T* _tlsSet(T*& var,T* new_o) 147 149 { 148 T* o=var;149 var=new_o;150 return o;150 T* o=var; 151 var=new_o; 152 return o; 151 153 } 152 154
Note: See TracChangeset
for help on using the changeset viewer.