Map pthread_t to linux thead ID

160 Views Asked by At

I have a service running on my linux server that exposes an API. The purpose of this API is to create a thread for the calling process that runs for a longer period of time. The purpose of the thread doesn't matter in this context.

The service that exposes the API keeps track of all created threads by storing them in a map:

# Class is just a placeholder for the actual implementation of my class.
std::map<pthread_t, Class>

The problem I'm facing is trying to map the pthread_t id to the corresponding thread id on my linux system.

When printing pthread_t the output is a unsigned long representation of the id which looks like this: 140638706251328.

When checking the running threads on my machine with the ps command, the TID looks similiar to this:

   TID     PID   PRI    RTPRIO   NI    COMMAND
   1350    1347  90     50        -    test

Is there any way to map the pthread_t to a linux TID?

1

There are 1 best solutions below

0
On

You can use syscall(SYS_gettid) or gettid() (Linux specific) to map tid and pthread_t, for example (no errors checkings) :

#include <pthread.h>
#include <sys/syscall.h> 
#include <unistd.h>

#include <iostream>

using namespace std;

static void *foo(void *arg)
{
    cout << "pthread_t " << pthread_self() << endl;
    cout << "thread tid " << syscall(SYS_gettid) << endl;
    cout << "thread gettid " << gettid() << endl; /* Linux specific */
    return nullptr;
}

int main()
{
    pthread_t t1;
    
    pthread_create(&t1, nullptr, foo, nullptr);
    pthread_join(t1, nullptr);

    return 0;
}