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

方法总结说明

  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 <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::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 							# 进程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
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抓饼先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值