获取系统级线程ID,第一次获取后就存起来,不再调用系统函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#pragma once

#include <sys/syscall.h>
#include <unistd.h>

class EventLoop;

namespace CurrentThread
{
inline thread_local int t_cachedTid = 0; //每个线程有自己专属的 ID 缓存。

//每个线程独有的 EventLoop*
inline thread_local EventLoop* t_loopInThisThread = nullptr;

inline int tid()
{
if(t_cachedTid == 0)
{
t_cachedTid = static_cast<pid_t>(::syscall(SYS_gettid));
}
return t_cachedTid;
}
};
  • thread_local:现代 C++ 关键字每个线程都有自己独立的变量,互不干扰

  • 函数前加inline,因为它是高频小函数(代码短,调用频繁,要求速度快),内联可以消除函数调用开销。

  • ::syscall(SYS_gettid)调用 Linux 内核 → 获取当前线程的系统 ID

  • static_cast<pid_t>(...)类型安全转换因为 syscall 返回 long,我们要存成 intpid_t就是int)。

  • inline 允许多个文件都定义,链接时自动合并成一个,防止多个头文件#include包含,引发重定义问题。

源码地址

CurrentThread.h:https://gitee.com/lpzdinghai/lpzmuduo/blob/master/CurrentThread.h