【问题标题】:How to map Linux system thread ids and std::thread::id?如何映射 Linux 系统线程 ID 和 std::thread::id?
【发布时间】: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-&gt;14012584756614431384-&gt;140125829990144

【问题讨论】:

  • 获取the underlying native handle怎么样?
  • 我也很好奇您要解决的潜在问题。 为什么你需要那个映射?用例是什么?
  • @Someprogrammerdude 我的输入是线程 ID,而不是 std::threads,所以没有什么可以得到底层的原生句柄。用例是检查进程的所有线程(包括由库内部创建的线程)的关联设置的正确性,并以这样一种方式报告不正确的线程,以便我可以轻松排除那些由我启动的线程。

标签: c++ linux c++11


【解决方案1】:

您需要自己访问std::thread 对象,并使用native_handle

或者您需要能够控制在这些线程上执行的内容,在这种情况下,您可以调用 std::this_thread::get_id 获取标准 ID,调用 pthread_self 获取本机 ID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    相关资源
    最近更新 更多