From 41239feb757e7a5b5f0b710b810010df016d4391 Mon Sep 17 00:00:00 2001 From: "Leandro A. F. Pereira" Date: Wed, 22 May 2019 08:17:26 -0700 Subject: [PATCH] Cache current thread ID in TLS (#24699) While looking at the strace of `corerun` built with logging and debugging information, I was amazed at the number of gettid() calls it was making. While system calls are cheap, they're still not free; cache this number in the thread local storage area. Adds a branch, but it's just a comparison with 0, so it's fine in comparison. --- src/pal/src/include/pal/thread.hpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/pal/src/include/pal/thread.hpp b/src/pal/src/include/pal/thread.hpp index dd48c23..6227b72 100644 --- a/src/pal/src/include/pal/thread.hpp +++ b/src/pal/src/include/pal/thread.hpp @@ -828,25 +828,32 @@ Abstract: --*/ #if defined(__linux__) -#define THREADSilentGetCurrentThreadId() (SIZE_T)syscall(SYS_gettid) +#define PlatformGetCurrentThreadId() (SIZE_T)syscall(SYS_gettid) #elif defined(__APPLE__) -inline SIZE_T THREADSilentGetCurrentThreadId() { +inline SIZE_T PlatformGetCurrentThreadId() { uint64_t tid; pthread_threadid_np(pthread_self(), &tid); return (SIZE_T)tid; } #elif defined(__FreeBSD__) #include -inline SIZE_T THREADSilentGetCurrentThreadId() { +inline SIZE_T PlatformGetCurrentThreadId() { long tid; thr_self(&tid); return (SIZE_T)tid; } #elif defined(__NetBSD__) #include -#define THREADSilentGetCurrentThreadId() (SIZE_T)_lwp_self() +#define PlatformGetCurrentThreadId() (SIZE_T)_lwp_self() #else -#define THREADSilentGetCurrentThreadId() (SIZE_T)pthread_self() +#define PlatformGetCurrentThreadId() (SIZE_T)pthread_self() #endif +inline SIZE_T THREADSilentGetCurrentThreadId() { + static __thread SIZE_T tid; + if (!tid) + tid = PlatformGetCurrentThreadId(); + return tid; +} + #endif // _PAL_THREAD_HPP_ -- 2.7.4