【发布时间】:2019-03-19 13:31:28
【问题描述】:
我可以通过/proc/self/task 枚举当前进程的所有线程的tid,如here 所述。如果我使用的库创建了一些线程,我如何将这些线程 ID 映射到 std::thread::id-s?
例如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();
}
打印这个:
main 140125847566144
tid: 31383
tid: 31384
thread 140125829990144
我希望能够建立对应关系:31383->140125847566144、31384->140125829990144。
【问题讨论】:
-
我也很好奇您要解决的潜在问题。 为什么你需要那个映射?用例是什么?
-
@Someprogrammerdude 我的输入是线程 ID,而不是
std::threads,所以没有什么可以得到底层的原生句柄。用例是检查进程的所有线程(包括由库内部创建的线程)的关联设置的正确性,并以这样一种方式报告不正确的线程,以便我可以轻松排除那些由我启动的线程。