ClickHouse/base/base/getThreadId.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

49 lines
1.1 KiB
C++
Raw Normal View History

2021-10-02 07:13:14 +00:00
#include <base/getThreadId.h>
2020-02-02 02:35:47 +00:00
2020-07-15 11:16:00 +00:00
#if defined(OS_ANDROID)
#include <sys/types.h>
#include <unistd.h>
#elif defined(OS_LINUX)
2020-02-02 20:05:47 +00:00
#include <unistd.h>
#include <syscall.h>
2020-05-10 05:24:01 +00:00
#elif defined(OS_FREEBSD)
2020-02-28 11:24:56 +00:00
#include <pthread_np.h>
2020-02-02 20:05:47 +00:00
#else
#include <pthread.h>
#include <stdexcept>
#endif
2020-02-02 02:35:47 +00:00
static thread_local uint64_t current_tid = 0;
2023-07-07 14:40:47 +00:00
static void setCurrentThreadId()
2020-02-02 02:35:47 +00:00
{
2020-07-15 11:16:00 +00:00
#if defined(OS_ANDROID)
2023-07-07 14:40:47 +00:00
current_tid = gettid();
2020-07-15 11:16:00 +00:00
#elif defined(OS_LINUX)
2023-07-07 14:40:47 +00:00
current_tid = static_cast<uint64_t>(syscall(SYS_gettid)); /// This call is always successful. - man gettid
2020-05-10 05:24:01 +00:00
#elif defined(OS_FREEBSD)
2023-07-07 14:40:47 +00:00
current_tid = pthread_getthreadid_np();
#elif defined(OS_SUNOS)
2023-07-07 14:40:47 +00:00
// On Solaris-derived systems, this returns the ID of the LWP, analogous
// to a thread.
current_tid = static_cast<uint64_t>(pthread_self());
2020-02-02 20:05:47 +00:00
#else
2023-07-07 14:40:47 +00:00
if (0 != pthread_threadid_np(nullptr, &current_tid))
throw std::logic_error("pthread_threadid_np returned error");
2020-02-02 20:05:47 +00:00
#endif
2023-07-07 14:40:47 +00:00
}
uint64_t getThreadId()
{
if (!current_tid)
setCurrentThreadId();
2020-02-02 02:35:47 +00:00
return current_tid;
}
2023-07-07 14:40:47 +00:00
void updateCurrentThreadIdAfterFork()
{
setCurrentThreadId();
}