C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 如何获得std :: thread()的Linux线程ID大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在玩std :: thread,我想知道如何获得一个新的std :: thread()的线程id,我不是在讨论std :: thread :: id而是提供给我的操作系统ID线程(您可以使用pstree查看它). @H_675_2@这仅仅是为了我的知识,它仅针对 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;
}

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

有什么建议吗?@H_675_2@谢谢.

解决方法

假设您正在使用GCC标准库,std :: thread :: native_handle()将返回pthread_self()返回的pthread_t线程ID,而不是gettid()返回的OS线程ID. 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();
}

然后创建你的线程:

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

大佬总结

以上是大佬教程为你收集整理的c – 如何获得std :: thread()的Linux线程ID全部内容,希望文章能够帮你解决c – 如何获得std :: thread()的Linux线程ID所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。