[英]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.