LinuxでスレッドIDを取得する方法のまとめ

方法の概要

  1. getpid()
    プロセス ID (メイン スレッド ID でもある) を取得するための Linux システム コール。

  2. gettid()
    スレッド ID を取得する Linux システム コール。
    C ランタイム ライブラリはこのインターフェイスをカプセル化しません。syscall() によって呼び出されます。
    メインスレッドでは、getpid = gettid になります。

  3. syscall(SYS_gettid) は、
    Linux システム コール (つまり、上記の gettid) を直接呼び出します。

  4. pthread_self()
    pthread ライブラリ関数は、pthread のスレッド ID を返します。
    この ID は gettid() の値とは異なります。実装が異なれば、異なる結果が返される場合があります。
    この関数を使用するには、コンパイル時に pthread ライブラリをリンクする必要があります。

  5. this_thread::get_id()
    tid を取得する C++ メソッド。戻り値は pthread_self() と同じです。
    戻り値の型はthread::idクラスであり、id値を直接取得することはできません。
    id クラスは出力演算子 << を提供します。これは stringstream を通じて変換して tid 値を取得できます。
    (規格委員会のお偉いさんが何を考えているのか分からない?というか本質を掴めていない)

テストコード

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

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

おすすめ

転載: blog.csdn.net/yinminsumeng/article/details/130268131