0

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?

Xershy
  • 177
  • 11
  • A `pthread_t` is meant to be an opaque type (so you shouldn't be printing it). I suspect you could store the result of `gettid()` in each thread, though, and use that for mapping, if you like. – Hasturkun Aug 30 '22 at 08:39

1 Answers1

0

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;
}
Employed Russian
  • 199,314
  • 34
  • 295
  • 362
Fryz
  • 2,119
  • 2
  • 25
  • 45