From b611811b346a865c43c5462bb10a7c55fb11c6d8 Mon Sep 17 00:00:00 2001 From: Adam Simpkins Date: Mon, 5 Jun 2017 19:07:36 -0700 Subject: [PATCH] add getOSThreadID() Summary: Add a getOSThreadID() call. This is similar to getCurrentThreadID(), but returns the OS-level thread ID. Reviewed By: yfeldblum Differential Revision: D5173627 fbshipit-source-id: 0e8695ecfc1e382d12526c1b7d1717be114c9f4a --- folly/ThreadId.h | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/folly/ThreadId.h b/folly/ThreadId.h index 6593b3f1..9896f874 100644 --- a/folly/ThreadId.h +++ b/folly/ThreadId.h @@ -19,10 +19,25 @@ #include #include +#include #include namespace folly { +/** + * Get a process-specific identifier for the current thread. + * + * The return value will uniquely identify the thread within the current + * process. + * + * Note that the return value does not necessarily correspond to an operating + * system thread ID. The return value is also only unique within the current + * process: getCurrentThreadID() may return the same value for two concurrently + * running threads in separate processes. + * + * The thread ID may be reused once the thread it corresponds to has been + * joined. + */ inline uint64_t getCurrentThreadID() { #if __APPLE__ return uint64_t(pthread_mach_thread_np(pthread_self())); @@ -32,4 +47,44 @@ inline uint64_t getCurrentThreadID() { return uint64_t(pthread_self()); #endif } + +/** + * Get the operating-system level thread ID for the current thread. + * + * The returned value will uniquely identify this thread on the system. + * + * This makes it more suitable for logging or displaying in user interfaces + * than the result of getCurrentThreadID(). + * + * There are some potential caveats about this API, however: + * + * - In theory there is no guarantee that application threads map one-to-one to + * kernel threads. An application threading implementation could potentially + * share one OS thread across multiple application threads, and/or it could + * potentially move application threads between different OS threads over + * time. However, in practice all of the platforms we currently support have + * a one-to-one mapping between userspace threads and operating system + * threads. + * + * - This API may also be slightly slower than getCurrentThreadID() on some + * platforms. This API may require a system call, where getCurrentThreadID() + * may only need to read thread-local memory. + * + * On Linux the returned value is a pid_t, and can be used in contexts + * requiring a thread pid_t. + * + * The thread ID may be reused once the thread it corresponds to has been + * joined. + */ +inline uint64_t getOSThreadID() { +#if __APPLE__ + uint64_t tid; + pthread_threadid_np(nullptr, &tid); + return tid; +#elif _WIN32 + return uint64_t(GetCurrentThreadId()); +#else + return uint64_t(syscall(FOLLY_SYS_gettid)); +#endif +} } -- 2.34.1