ClickHouse/base/common/getThreadId.cpp

31 lines
655 B
C++
Raw Normal View History

#include <common/getThreadId.h>
2020-02-02 02:35:47 +00:00
2020-02-02 20:05:47 +00:00
#if OS_LINUX
#include <unistd.h>
#include <syscall.h>
2020-02-28 11:24:56 +00:00
#elif OS_FREEBSD
#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
{
#if OS_LINUX
2020-02-02 02:35:47 +00:00
current_tid = syscall(SYS_gettid); /// This call is always successful. - man gettid
2020-02-28 11:24:56 +00:00
#elif OS_FREEBSD
current_tid = pthread_getthreadid_np();
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;
}