muduo CurrentThread

文章目录
  1. 1. 参考资料
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#ifndef MUDUO_BASE_CURRENTTHREAD_H
#define MUDUO_BASE_CURRENTTHREAD_H

#include "muduo/base/Types.h"

namespace muduo
{
namespace CurrentThread
{
// internal
// 使用 __thread 修饰变量 使得每一个线程都有一份独立实体,各个线程的值互不干扰
extern __thread int t_cachedTid; // 当前线程id
extern __thread char t_tidString[32]; // 当前线程id
extern __thread int t_tidStringLength; // char 的大小
extern __thread const char* t_threadName; // 线程名字

void cacheTid();

inline int tid()
{
if (__builtin_expect(t_cachedTid == 0, 0))
{
cacheTid();
}
return t_cachedTid;
}

inline const char* tidString() // for logging
{
return t_tidString;
}

inline int tidStringLength() // for logging
{
return t_tidStringLength;
}

inline const char* name()
{
return t_threadName;
}

bool isMainThread();

void sleepUsec(int64_t usec); // for testing

string stackTrace(bool demangle);
} // namespace CurrentThread
} // namespace muduo

#endif // MUDUO_BASE_CURRENTTHREAD_H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
namespace muduo
{
namespace CurrentThread
{
__thread int t_cachedTid = 0;
__thread char t_tidString[32];
__thread int t_tidStringLength = 6;
__thread const char* t_threadName = "unknown";
static_assert(std::is_same<int, pid_t>::value, "pid_t should be int");

string stackTrace(bool demangle)
{
string stack;
const int max_frames = 200;
void* frame[max_frames];
int nptrs = ::backtrace(frame, max_frames);
char** strings = ::backtrace_symbols(frame, nptrs);
if (strings)
{
size_t len = 256;
char* demangled = demangle ? static_cast<char*>(::malloc(len)) : nullptr;
for (int i = 1; i < nptrs; ++i) // skipping the 0-th, which is this function
{
if (demangle)
{
// https://panthema.net/2008/0901-stacktrace-demangled/
// bin/exception_test(_ZN3Bar4testEv+0x79) [0x401909]
char* left_par = nullptr;
char* plus = nullptr;
for (char* p = strings[i]; *p; ++p)
{
if (*p == '(')
left_par = p;
else if (*p == '+')
plus = p;
}

if (left_par && plus)
{
*plus = '\0';
int status = 0;
char* ret = abi::__cxa_demangle(left_par+1, demangled, &len, &status);
*plus = '+';
if (status == 0)
{
demangled = ret; // ret could be realloc()
stack.append(strings[i], left_par+1);
stack.append(demangled);
stack.append(plus);
stack.push_back('\n');
continue;
}
}
}
// Fallback to mangled names
stack.append(strings[i]);
stack.push_back('\n');
}
free(demangled);
free(strings);
}
return stack;
}

} // namespace CurrentThread
} // namespace muduo

参考资料