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 */
#endif
}
+static unsigned next_thread_id = 0;
+static os::thread_specific_ptr<unsigned> thread_id_specific_ptr;
+
unsigned LocalWriter::beginEnter(const FunctionSig *sig) {
os::acquireMutex();
++acquired;
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<unsigned>(id));
+ return Writer::beginEnter(sig, thread_id);
}
void LocalWriter::endEnter(void) {