Summary of methods for obtaining thread id under Linux

Method summary

  1. getpid()
    Linux system call to get the process id, which is also the main thread id.

  2. gettid()
    Linux system call to get the thread id.
    The C runtime library does not encapsulate this interface...it is called by syscall().
    In the main thread, getpid = gettid.

  3. syscall(SYS_gettid)
    directly calls the Linux system call (ie gettid above).

  4. pthread_self()
    pthread library function, returns the thread id in pthread.
    This id is different from the value of gettid(). Different implementations may return different results.
    To use this function, the pthread library needs to be linked at compile time.

  5. this_thread::get_id()
    C++ method to get tid, the return value is the same as pthread_self().
    The return type is the thread::id class, and the id value cannot be obtained directly.
    The id class provides an output operator <<, which can be converted through stringstream to get the tid value.
    (I don’t know what the big guys in the standard committee think? Or I haven’t grasped the essence)

test code

#include <sys/syscall.h>   /* For SYS_xxx definitions */
#include <iostream>
#include <unistd.h>
#include <thread>
#include <sys/types.h>
#include <csignal>
#include <sstream>

using namespace std;

void printId() {
    
    
    cout << "getpid: " << getpid() << endl;
//    cout << "gettid: " << gettid() << endl;
    pid_t tid;
    tid = syscall(SYS_gettid);
    printf("syscall gettid: %d\n", tid);

    cout << "pthread_self:" << pthread_self() << endl;
    cout << "this_thread::get_id: " << this_thread::get_id() << endl;

    stringstream stream;
    string pidStr;
    stream << this_thread::get_id(); // return type: class thread::id
    stream >> pidStr;
    printf("convert pid: [%s]\n", pidStr.c_str());

    cout << endl << endl;
}

int main() {
    
    

    printId();

    for (int i=0; i<3; i++) {
    
    
        thread th(printId);
        th.detach();
    }

    std::cout << "Hello, World!" << std::endl;

    sleep(10);
    return 0;
}

Compile and run results on Ubuntu

# 主线程
getpid: 7257 							# 进程id
syscall gettid: 7257 					# 线程id,主线程,同进程id
pthread_self: 140489738667840
this_thread::get_id: 140489738667840 	# 结果和pthread_self相同
convert pid: [140489738667840] 			# 转换后获取到的tid


# 新线程
getpid: 7257							# 进程id,不变
syscall gettid: 7258					#不同的线程id
pthread_self: 140489716274944			# 不同线程id
this_thread::get_id: 140489716274944
convert pid: [140489716274944]

......

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/yinminsumeng/article/details/130268131