1#include <pthread.h>
2
3#if defined(__APPLE__)
4#elif defined(__FreeBSD__)
5 #include <pthread_np.h>
6#else
7 #include <sys/prctl.h>
8#endif
9
10#include <cstring>
11
12#include <Common/Exception.h>
13#include <Common/setThreadName.h>
14
15
16namespace DB
17{
18namespace ErrorCodes
19{
20 extern const int PTHREAD_ERROR;
21}
22}
23
24
25void setThreadName(const char * name)
26{
27#ifndef NDEBUG
28 if (strlen(name) > 15)
29 throw DB::Exception("Thread name cannot be longer than 15 bytes", DB::ErrorCodes::PTHREAD_ERROR);
30#endif
31
32#if defined(__FreeBSD__)
33 pthread_set_name_np(pthread_self(), name);
34 return;
35
36#elif defined(__APPLE__)
37 if (0 != pthread_setname_np(name))
38#else
39 if (0 != prctl(PR_SET_NAME, name, 0, 0, 0))
40#endif
41 DB::throwFromErrno("Cannot set thread name with prctl(PR_SET_NAME, ...)", DB::ErrorCodes::PTHREAD_ERROR);
42}
43
44std::string getThreadName()
45{
46 std::string name(16, '\0');
47
48#if defined(__APPLE__)
49 if (pthread_getname_np(pthread_self(), name.data(), name.size()))
50 throw DB::Exception("Cannot get thread name with pthread_getname_np()", DB::ErrorCodes::PTHREAD_ERROR);
51#elif defined(__FreeBSD__)
52// TODO: make test. freebsd will have this function soon https://freshbsd.org/commit/freebsd/r337983
53// if (pthread_get_name_np(pthread_self(), name.data(), name.size()))
54// throw DB::Exception("Cannot get thread name with pthread_get_name_np()", DB::ErrorCodes::PTHREAD_ERROR);
55#else
56 if (0 != prctl(PR_GET_NAME, name.data(), 0, 0, 0))
57 DB::throwFromErrno("Cannot get thread name with prctl(PR_GET_NAME)", DB::ErrorCodes::PTHREAD_ERROR);
58#endif
59
60 name.resize(std::strlen(name.data()));
61 return name;
62}
63