Search code examples
c++linuxmultithreading

Why am i getting different values from this_thread::get_id() and gettid()?


I was reading threads and concurrency and hit this quote:

std::this_thread::get_id() return the id of the thread calling it.

So, I wrote the following code to test the function and see if it's doing something else than what Uniux's gettid() does:

#include <iostream>
#include <thread>
#include <chrono>
#include <unistd.h>

using namespace std;

void someFunction(){
  int i = 0;
  while(i++ < 2){
    cout<<"TID using gettid(): "<< gettid()<<endl;
    cout<<"TID using this_thread::get_id: "<< this_thread::get_id()<<endl<<endl;
    std::this_thread::sleep_for(chrono::milliseconds(900));    
  }
}

int main(){
  cout<<"Hello from main"<<endl;
  cout<<"TID using gettid(): "<<gettid()<<endl;
  cout<<"TID using this_thread::get_id(): "<<this_thread::get_id()<<endl<<endl;
  
  thread testThread(someFunction);
  testThread.join();

  return 0;
}

The output shows that the two functions are returning different values and my question is why? is this related to pths and pthreads?


Solution

  • The gettid() is a Linux specific system call returning the thread ID of the thread calling it. The returning type is a pid_t (an integer) as written in the man page https://man7.org/linux/man-pages/man2/gettid.2.html There's no guarantee that this system call return the same number as the POSIX thread ID.

    The C++ function std::this_thread::get_id() is part of the C++ standard and it's completely different. It's purpose is to identify threads in different systems (not specifically Linux). Moreover, the type returned by this function is not an integer but it's a std::thread::id and you can print it to your console only because its << operator is overloaded.

    https://en.cppreference.com/w/cpp/thread/thread/id