方法总结说明 getpid() linux系统调用,获取进程id,也是主线程id。 gettid() Linux系统调用,获取线程id。 C运行库没有封装这个接口…用syscall()方式调用。 在主线程中,getpid = getti
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 #include #include #include #include #include #include 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::id stream >> 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;}
# 主线程getpid: 7257 # 进程idsyscall gettid: 7257 # 线程id,主线程,同进程idpthread_self: 140489738667840this_thread::get_id: 140489738667840 # 结果和pthread_self相同convert pid: [140489738667840] # 转换后获取到的tid# 新线程getpid: 7257# 进程id,不变syscall gettid: 7258#不同的线程idpthread_self: 140489716274944# 不同线程idthis_thread::get_id: 140489716274944convert pid: [140489716274944]......Process finished with exit code 0
来源地址:https://blog.csdn.net/yinminsumeng/article/details/130268131
--结束END--
本文标题: Linux下获取线程id的方法总结
本文链接: https://www.lsjlt.com/news/374468.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0