c++获取线程id

c++11的thread库提供了获取tid的接口:

std::this_thread::get_id()

这个接口返回的是一个内存地址指向表述线程的结构体(pthread也是一样)。

有的时候这种方式获取的pid过长,可以使用syscall获取lwp,也就是top -H中看到的id,但也要注意syscall造成的的开销:

 1 #include <iostream>
 2 #include <unistd.h>
 3 #include <sys/syscall.h>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     int tid = syscall(SYS_gettid);
10     cout << tid <<endl;
11     return 0;
12 }
原文地址:https://www.cnblogs.com/HadesBlog/p/13162994.html