iis服务器助手广告广告
返回顶部
首页 > 资讯 > 操作系统 >Linux下获取线程id的方法总结
  • 650
分享到

Linux下获取线程id的方法总结

linux服务器c++开发语言ubuntu 2023-08-18 17:08:34 650人浏览 泡泡鱼
摘要

方法总结说明 getpid() linux系统调用,获取进程id,也是主线程id。 gettid() Linux系统调用,获取线程id。 C运行库没有封装这个接口…用syscall()方式调用。 在主线程中,getpid = getti

方法总结说明

  1. getpid()
    linux系统调用,获取进程id,也是主线程id。

  2. gettid()
    Linux系统调用,获取线程id。
    C运行库没有封装这个接口…用syscall()方式调用。
    在主线程中,getpid = gettid。

  3. syscall(SYS_gettid)
    直接调用Linux系统调用(即上面的gettid)。

  4. pthread_self()
    pthread库函数,返回pthread中的线程id。
    这个id不同于gettid()的值。不同的实现可能返回不同的结果。
    使用这个函数,需要在编译时链接pthread库。

  5. 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;}

ubuntu上编译、运行结果

# 主线程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文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作