方法总结说明
-
getpid()
Linux系统调用,获取进程id,也是主线程id。 -
gettid()
Linux系统调用,获取线程id。
C运行库没有封装这个接口…用syscall()方式调用。
在主线程中,getpid = gettid。 -
syscall(SYS_gettid)
直接调用Linux系统调用(即上面的gettid)。 -
pthread_self()
pthread库函数,返回pthread中的线程id。
这个id不同于gettid()的值。不同的实现可能返回不同的结果。
使用这个函数,需要在编译时链接pthread库。 -
this_thread::get_id()
C++获取tid方法,返回值和pthread_self()相同。
返回类型是thread::id类,不能直接拿到id值。
id类提供了一个输出运算符<<,通过stringstream转换一下拿到tid值。
(不知道标准委员会的大咖们怎么想的?还是我没有领会到精髓)
测试代码
#include <sys/syscall.h> /* For SYS_xxx definitions */
#include <iostream>
#include <unistd.h>
#include <thread>
#include <sys/types.h>
#include <csignal>
#include <sstream>using namespace std;void printId() {cout << "getpid: " << getpid() << endl;
// cout << "gettid: " << gettid() << endl;pid_t tid;tid = syscall(SYS_gettid);printf("syscall gettid: %d\n", tid);cout << "pthread_self:" << pthread_self() << endl;cout << "this_thread::get_id: " << this_thread::get_id() << endl;stringstream stream;string pidStr;stream << this_thread::get_id(); // return type: class thread::idstream >> pidStr;printf("convert pid: [%s]\n", pidStr.c_str());cout << endl << endl;
}int main() {printId();for (int i=0; i<3; i++) {thread th(printId);th.detach();}std::cout << "Hello, World!" << std::endl;sleep(10);return 0;
}
Ubuntu上编译、运行结果
# 主线程
getpid: 7257 # 进程id
syscall gettid: 7257 # 线程id,主线程,同进程id
pthread_self: 140489738667840
this_thread::get_id: 140489738667840 # 结果和pthread_self相同
convert pid: [140489738667840] # 转换后获取到的tid# 新线程
getpid: 7257 # 进程id,不变
syscall gettid: 7258 #不同的线程id
pthread_self: 140489716274944 # 不同线程id
this_thread::get_id: 140489716274944
convert pid: [140489716274944]......Process finished with exit code 0