c++ - 如何映射 Linux 系统线程 ID 和 std::thread::id?
问题描述
我可以通过这里/proc/self/task
描述的方式枚举当前进程的所有线程的 tid 。如果我使用的库创建了一些线程,我如何将这些线程 ID 映射到-s?std::thread::id
例如,这个程序:
#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
.
解决方案
您需要有权访问std::thread
对象本身,并使用native_handle
.
或者您需要能够控制在这些线程上执行的内容,在这种情况下您可以调用std::this_thread::get_id
标准 ID 和pthread_self
本机 ID。
推荐阅读
- ruby-on-rails - 在 Rails 中禁用 SSL 重定向的方法
- python-3.x - 基本 If 语句单元测试
- python - 如何让我的变量成为 tkinter 中输入框的输入?
- xcode - Xcode 12.0 调试视图不显示变量
- python - Django 3.1.1 未找到静态文件
- javascript - 调整大小和移动多边形后如何获取多边形点的新位置
- prolog - 为什么这个序言的输出是yes/true?
- pine-script - 在交易视图版本 4 的价格图表上绘制/叠加基本数据“EPS”
- python - Azure 函数使用 ssh 访问私有 github 存储库
- reactjs - 当传递不同的 prop 值时,React 组件不会以动态方式工作