Linux下获取线程ID

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Linux下获取线程ID脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Linux下获取线程ID

获取内核线程的ID,在<Sys/tyPEs.h>头文件中, 当只有一个线程的时候,返回的是pid。

#include <sys/types.h>
pid_t gettid(void);

但是文档说glibc并没有做封装,需要调用syscall才行。

#include <sys/syscall.h>  
#define gettid() syscall(__NR_gettid)

C++标准线程库函数

#include <thread>
std::this_thread::get_id();

pthread函数

#include <pthread.h>
pthread_t pthread_self(void);

下面这段代码,只有一个线程,所以getpid和gettid获取到的值是一样的,std::this_thread::get_id()在linux下只是对pthread进行封装,所以pthread_self()是一样的。

#include <pthread.h>
#include <thread>
#include <iostream>
#include <unistd.h>
#include <stdio.h>

#include <sys/syscall.h>  
#define gettid() syscall(__NR_gettid)

using namespace std;

int main()
{
    cout<<"process id: "<<getpid()<<endl;
    cout<<"kernel id: "<<gettid()<<endl;
    cout<<"std thread id: "<< std::this_thread::get_id()<<endl;
    cout<<"pthread id:"<< pthread_self()<<endl;
    return 0;
}

脚本宝典总结

以上是脚本宝典为你收集整理的Linux下获取线程ID全部内容,希望文章能够帮你解决Linux下获取线程ID所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。