]> git.cworth.org Git - apitrace/blobdiff - common/os_thread.hpp
Use thread local storage to specify unique and low integer thread ids.
[apitrace] / common / os_thread.hpp
index 727ad6a484ff0c94a1e8d76bd4a88a3dd846dc15..7349255525276b47b36c3b5ba5aa7e3c4f4b6d81 100644 (file)
 namespace os {
 
 
-    namespace thread {
-
-        /**
-         * Thread ID
-         *
-         * XXX: Actually C++11 thread::id is not an integral type, but we rely on that.
-         */
+    template <typename T>
+    class thread_specific_ptr
+    {
+    private:
 #ifdef _WIN32
-        typedef DWORD id;
+        DWORD dwTlsIndex;
 #else
-        typedef pthread_t id;
-#endif
+        pthread_key_t key;
 
-    } /* namespace thread */
+        static void destructor(void *ptr) {
+            delete static_cast<T *>(ptr);
+        }
+#endif
 
+    public:
+        thread_specific_ptr(void) {
+#ifdef _WIN32
+            dwTlsIndex = TlsAlloc();
+#else
+            pthread_key_create(&key, &destructor);
+#endif
+        }
 
-    namespace this_thread {
+        ~thread_specific_ptr() {
+#ifdef _WIN32
+            TlsFree(dwTlsIndex);
+#else
+            pthread_key_delete(key);
+#endif
+        }
 
-        /**
-         * Get current thread ID.
-         */
-        inline thread::id
-        get_id(void) {
+        T* get(void) const {
+            void *ptr;
 #ifdef _WIN32
-            return GetCurrentThreadId();
+            ptr = TlsGetValue(dwTlsIndex);
 #else
-            return pthread_self();
+            ptr = pthread_getspecific(key);
 #endif
+            return static_cast<T*>(ptr);
         }
 
-    } /* namespace this_thread */
+        T* operator -> (void) const
+        {
+            return get();
+        }
+
+        T& operator * (void) const
+        {
+            return *get();
+        }
 
+        void reset(T* new_value=0) {
+            T * old_value = get();
+#ifdef _WIN32
+            TlsSetValue(dwTlsIndex, new_value);
+#else
+            pthread_setspecific(key, new_value);
+#endif
+            if (old_value) {
+                delete old_value;
+            }
+        }
+    };
 
 } /* namespace os */