0

I can enumerate tids of all threads of current process via /proc/self/task as described here. How can I map these thread ids to std::thread::id-s in case there are some threads created by libraries that I use?

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.

Dev Null
  • 4,731
  • 1
  • 30
  • 46
  • 1
    How about getting [the underlying native handle](https://en.cppreference.com/w/cpp/thread/thread/native_handle)? – Some programmer dude Oct 15 '18 at 07:06
  • I'm also curious about the underlying problem you're trying to solve. *Why* do you need that mapping? What is the use-case? – Some programmer dude Oct 15 '18 at 07:07
  • 1
    @Someprogrammerdude my input is thread ids, not `std::threads`, so there's nothing to get the underlying native handle on. The usecase is to check correctness of affinity settings for all threads of the process, including those created by libraries internally, and report incorrect threads in such a way that I can easily exclude those that were started by me. – Dev Null Oct 15 '18 at 07:13

1 Answers1

0

You need to either have access to the std::thread objects themselves, and use 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.

eerorika
  • 232,697
  • 12
  • 197
  • 326