16

我在玩,std::thread我想知道如何获得一个新的线程 id std::thread(),我不是在谈论,std::thread::id而是给线程的 OS Id(你可以使用它查看它pstree)。这只是为了我的知识,它只针对 Linux 平台(不需要是可移植的)。

我可以像这样在线程中获取 Linux 线程 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;
}

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

有什么建议吗?谢谢你。

4

3 回答 3

13

假设您使用的是 GCC 标准库,则返回由 .std::thread::native_handle()返回的pthread_t线程 ID pthread_self(),而不是由gettid(). std::thread::id()是相同的包装器pthread_t,并且 GCCstd::thread不提供任何获取 OS 线程 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();
}

然后创建你的线程:

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

然后通过以下方式获取 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()];
}
于 2013-03-29T20:49:01.463 回答
1

一些 pthread实现,例如Android 21 +,提供

pid_t pthread_gettid_np(pthread_t);

该实现可以使用 的内部结构struct pthread_t来检索本机线程 ID,与由该线程返回gettid()syscall(SYS_gettid)在该线程的上下文中调用时返回的 ID 相同。

于 2017-08-22T18:15:02.830 回答
0

这个怎么样:

pid_t gettid (void)
{
    return syscall(__NR_gettid);
}

http://yusufonlinux.blogspot.com/2010/11/get-thread-id-from-linux.html

看起来 __NR_gettid 是在 unistd.h 中定义的

于 2013-03-29T18:26:30.173 回答