1

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

talentwill
18 声望0 粉丝