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 }