From ff5706c28bd6efb1a258ef5150647b93c6815f99 Mon Sep 17 00:00:00 2001 From: SchulzCode <116190857+SchulzCode@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:03:37 +0100 Subject: [PATCH] Cache the thread id per thread on Linux plat_thread_id() made a gettid syscall on every call, about 700,000 times a second in the open world (plat_rmutex_lock asks on every acquire). A thread's id never changes and the runtime does not fork, so the first call on each thread keeps it in a thread-local. noinline keeps a caller from reusing the thread-local's address across a fiber switch, since a fiber may resume on another thread. Fixes #236. --- runtime/platform/linux.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/runtime/platform/linux.c b/runtime/platform/linux.c index 0b9f572a..c28bff64 100644 --- a/runtime/platform/linux.c +++ b/runtime/platform/linux.c @@ -1172,7 +1172,17 @@ size_t plat_getenv(const char *name, char *out, size_t cap) { return n; } -uint32_t plat_thread_id(void) { return (uint32_t)syscall(SYS_gettid); } +// The kernel's id of the calling thread, kept per thread after the first call. The runtime asks for it about 700,000 +// times a second in the open world (plat_rmutex_lock in common.c, on every acquire), and syscall(SYS_gettid) enters the +// kernel each time. +// A thread's id never changes, and the runtime does not fork. noinline: a fiber may resume on another thread +// (platform.h), and a caller that inlined this could reuse the address of tid it computed before a plat_fiber_switch; +// as a call it reads the slot of the thread it runs on, as the syscall did. +__attribute__((noinline)) uint32_t plat_thread_id(void) { + static __thread uint32_t tid; + if (!tid) tid = (uint32_t)syscall(SYS_gettid); + return tid; +} // The first set variable of names ("ru_RU.UTF-8") as a BCP-47 tag ("ru-RU") into tag; "" for C and POSIX. static void locale_tag(const char *const *names, int n, char *tag, size_t cap) {