你怎么能得到一个std :: thread()的Linux线程ID

Cha*_*ble 11 c++ multithreading pthreads c++11

我正在玩,std::thread我想知道如何获得一个新的线程ID std::thread(),我不是在讨论,std::thread::id而是提供给线程的操作系统ID(您可以使用它查看pstree).这仅限于我的知识,它仅针对Linux平台(无需可移植).

我可以像这样在线程中获取Linux Thread Id:

#include <iostream>
#include <thread>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>

void SayHello()
{
    std::cout << "Hello ! my id is " << (long int)syscall(SYS_gettid) << std::endl;
}

int main (int argc, char *argv[])
{
    std::thread t1(&SayHello);
    t1.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是如何在主循环中检索相同的id?我找不到使用的方法 std::thread::native_handle.我认为有可能pid_t gettid(void);通过c ++ 11实现依赖于pthreads来实现它,但我一定是错的.

有什么建议吗?谢谢.

Jon*_*ely 6

假设您正在使用GCC标准库,则std::thread::native_handle()返回返回的pthread_t线程ID pthread_self(),而不是返回的OS线程ID gettid().std::thread::id()是一个包装器pthread_t,并且GCC std::thread没有提供任何获取操作系统线程ID的方法,但您可以创建自己的映射:

std::mutex m;
std::map<std::thread::id, pid_t> threads;
void add_tid_mapping()
{
  std::lock_guard<std::mutex> l(m);
  threads[std::this_thread::get_id()] = syscall(SYS_gettid);
}
void wrap(void (*f)())
{
  add_tid_mapping();
  f();
}
Run Code Online (Sandbox Code Playgroud)

然后创建你的线程:

std::thread t1(&wrap, &SayHello);
Run Code Online (Sandbox Code Playgroud)

然后通过以下方式获取ID:

pid_t tid = 0;
while (tid == 0)
{
  std::lock_guard<std::mutex> l(m);
  if (threads.count(t1.get_id()))
    tid = threads[t1.get_id()];
}
Run Code Online (Sandbox Code Playgroud)