本文介绍了如何获得std :: thread()的Linux线程ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩std::thread,我想知道如何获得新std::thread()的线程ID,我不是在谈论std::thread::id,而是为线程指定了OS ID(您可以使用pstree查看它).这仅是我所知,并且仅针对Linux平台(无需便携式).

I was playing with std::thread and I was wondering how is it possible to get the thread id of a new std::thread(), I am not talking about std::thread::id but rather the OS Id given to the thread ( you can view it using pstree).This is only for my knowledge, and it's targeted only to Linux platforms (no need to be portable).

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

I can get the Linux Thread Id within the thread like this :

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

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

But how can I retrieve the same id within the main loop ? I did not find a way using std::thread::native_handle. I believed it was possible to get it trough pid_t gettid(void); since the c++11 implementation relies on pthreads, but i must be wrong.

有什么建议吗?谢谢.

Any advices ?Thank you.

推荐答案

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

Assuming you're using GCC standard library, std::thread::native_handle() returns the pthread_t thread ID returned by pthread_self(), not the OS thread ID returned by gettid(). std::thread::id() is a wrapper around that same pthread_t, and GCC's std::thread doesn't provide any way to get the OS thread ID, but you could create your own mapping:

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();
}

然后使用以下方法创建您的线程:

Then create your thread with:

std::thread t1(&wrap, &SayHello);

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

then get the ID with something like:

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()];
}

这篇关于如何获得std :: thread()的Linux线程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:06