繁体   English   中英

如何映射Linux系统线程ID和std :: thread :: id?

[英]How to map Linux system thread ids and std::thread::id?

我可以通过枚举当前进程的所有线程的TIDS /proc/self/task描述这里 如果我使用的库创建了一些线程,如何将这些线程ID映射到std::thread::id -s?

例如, 该程序

#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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM