Skip to content

Commit 41239fe

Browse files
lpereirajanvorli
authored andcommitted
Cache current thread ID in TLS (dotnet#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.
1 parent aa66f12 commit 41239fe

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/pal/src/include/pal/thread.hpp

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -828,25 +828,32 @@ extern PAL_SafeActivationCheckFunction g_safeActivationCheckFunction;
828828
829829
--*/
830830
#if defined(__linux__)
831-
#define THREADSilentGetCurrentThreadId() (SIZE_T)syscall(SYS_gettid)
831+
#define PlatformGetCurrentThreadId() (SIZE_T)syscall(SYS_gettid)
832832
#elif defined(__APPLE__)
833-
inline SIZE_T THREADSilentGetCurrentThreadId() {
833+
inline SIZE_T PlatformGetCurrentThreadId() {
834834
uint64_t tid;
835835
pthread_threadid_np(pthread_self(), &tid);
836836
return (SIZE_T)tid;
837837
}
838838
#elif defined(__FreeBSD__)
839839
#include <sys/thr.h>
840-
inline SIZE_T THREADSilentGetCurrentThreadId() {
840+
inline SIZE_T PlatformGetCurrentThreadId() {
841841
long tid;
842842
thr_self(&tid);
843843
return (SIZE_T)tid;
844844
}
845845
#elif defined(__NetBSD__)
846846
#include <lwp.h>
847-
#define THREADSilentGetCurrentThreadId() (SIZE_T)_lwp_self()
847+
#define PlatformGetCurrentThreadId() (SIZE_T)_lwp_self()
848848
#else
849-
#define THREADSilentGetCurrentThreadId() (SIZE_T)pthread_self()
849+
#define PlatformGetCurrentThreadId() (SIZE_T)pthread_self()
850850
#endif
851851

852+
inline SIZE_T THREADSilentGetCurrentThreadId() {
853+
static __thread SIZE_T tid;
854+
if (!tid)
855+
tid = PlatformGetCurrentThreadId();
856+
return tid;
857+
}
858+
852859
#endif // _PAL_THREAD_HPP_

0 commit comments

Comments
 (0)