[英]How to map Linux system thread ids and std::thread::id?
I can enumerate tids of all threads of current process via /proc/self/task
as described here . 我可以通过枚举当前进程的所有线程的TIDS /proc/self/task
描述这里 。 How can I map these thread ids to std::thread::id
-s in case there are some threads created by libraries that I use? 如果我使用的库创建了一些线程,如何将这些线程ID映射到std::thread::id
-s?
For example, this program : 例如, 该程序 :
#include <iostream>
#include <thread>
#include <vector>
#include <errno.h>
#include <sched.h>
#include <sys/types.h>
#include <dirent.h>
int main()
{
auto get_thread_ids = [] () -> std::vector<int>
{
std::unique_ptr<DIR, int (*)(DIR*)> self_dir{opendir("/proc/self/task"), &closedir};
if (!self_dir)
return {};
std::vector<int> ret{};
struct dirent *entry = nullptr;
while ((entry = readdir(self_dir.get())) != nullptr)
{
if (entry->d_name[0] == '.')
continue;
ret.emplace_back(std::stoi(entry->d_name));
}
return ret;
};
std::cout << "main " << std::this_thread::get_id() << std::endl;
std::thread t{
[](){
std::cout << "thread " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds{5});
}
};
for (const auto& i : get_thread_ids())
std::cout << "tid: " << i << std::endl;
t.join();
}
prints this: 打印此:
main 140125847566144
tid: 31383
tid: 31384
thread 140125829990144
I want to be able to establish correspondence: 31383->140125847566144
, 31384->140125829990144
. 我想能够建立对应关系: 31383->140125847566144
31384->140125829990144
。
You need to either have access to the std::thread
objects themselves, and use native_handle
. 您需要访问std::thread
对象本身,并使用native_handle
。
Or you need to be able to control what is executed on those threads in which case you can call std::this_thread::get_id
for the standard ID and pthread_self
for the native ID. 或者,您需要能够控制在这些线程上执行的操作,在这种情况下,您可以将std::this_thread::get_id
用作标准ID,将pthread_self
用作本机ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.