ClickHouse/base/common/getThreadId.cpp

40 lines
1016 B
C++
Raw Normal View History

#include <common/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;
uint64_t getThreadId()
2020-02-02 02:35:47 +00:00
{
if (!current_tid)
2020-02-02 20:05:47 +00:00
{
2020-07-15 11:16:00 +00:00
#if defined(OS_ANDROID)
current_tid = gettid();
#elif defined(OS_LINUX)
2020-02-02 02:35:47 +00:00
current_tid = syscall(SYS_gettid); /// This call is always successful. - man gettid
2020-05-10 05:24:01 +00:00
#elif defined(OS_FREEBSD)
2020-02-28 11:24:56 +00:00
current_tid = pthread_getthreadid_np();
#elif defined(OS_SUNOS)
// 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
2020-02-02 22:51:40 +00:00
if (0 != pthread_threadid_np(nullptr, &current_tid))
2020-02-02 20:05:47 +00:00
throw std::logic_error("pthread_threadid_np returned error");
#endif
}
2020-02-02 02:35:47 +00:00
return current_tid;
}