大佬教程收集整理的这篇文章主要介绍了c – 如何获得std :: thread()的Linux线程ID,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以像这样在线程中获取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@谢谢.
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,请注明来意。