From: José Fonseca Date: Thu, 22 Dec 2011 22:19:40 +0000 (+0000) Subject: Use thread local storage to specify unique and low integer thread ids. X-Git-Url: https://git.cworth.org/git?a=commitdiff_plain;h=5926761f1682c26266a78f2674e58beff3bfae88;p=apitrace Use thread local storage to specify unique and low integer thread ids. --- diff --git a/common/os_thread.hpp b/common/os_thread.hpp index 727ad6a..7349255 100644 --- a/common/os_thread.hpp +++ b/common/os_thread.hpp @@ -41,38 +41,69 @@ namespace os { - namespace thread { - - /** - * Thread ID - * - * XXX: Actually C++11 thread::id is not an integral type, but we rely on that. - */ + template + 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(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(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 */ diff --git a/common/trace_writer_local.cpp b/common/trace_writer_local.cpp index bb06d90..77c8bd6 100644 --- a/common/trace_writer_local.cpp +++ b/common/trace_writer_local.cpp @@ -124,6 +124,9 @@ LocalWriter::open(void) { #endif } +static unsigned next_thread_id = 0; +static os::thread_specific_ptr thread_id_specific_ptr; + unsigned LocalWriter::beginEnter(const FunctionSig *sig) { os::acquireMutex(); ++acquired; @@ -132,9 +135,18 @@ unsigned LocalWriter::beginEnter(const FunctionSig *sig) { open(); } - os::thread::id id = os::this_thread::get_id(); + unsigned *thread_id_ptr = thread_id_specific_ptr.get(); + unsigned thread_id; + if (thread_id_ptr) { + thread_id = *thread_id_ptr; + } else { + thread_id = next_thread_id++; + thread_id_ptr = new unsigned; + *thread_id_ptr = thread_id; + thread_id_specific_ptr.reset(thread_id_ptr); + } - return Writer::beginEnter(sig, static_cast(id)); + return Writer::beginEnter(sig, thread_id); } void LocalWriter::endEnter(void) {