如何用线程获取c++中的父id



我想知道如何从创建的线程中获取父id。我有一个想法,我在主函数中创建一个id变量,并在创建线程时将其作为参数,但它不起作用。或者我可以获得父母id吗?

我的代码:

void first(std::thread::id id) {
//do something
cout << id << endl;
}
int main() {
std::thread::id id = std::this_thread::get_id();
std::thread thread(first, id);
return 0;
}

你的想法是什么?

程序

#include <iostream>
#include <thread>
void first(std::thread::id id) {
std::cout << "ID in thread: "<< id << std::endl;
std::thread::id ownID = std::this_thread::get_id();
std::cout << "ID of thread: " << ownID << std::endl;
}
int main() {
std::thread::id id = std::this_thread::get_id();
std::cout << "ID in main: " << id << std::endl;
std::thread thread(first, id);
thread.join();
return 0;
}

生成输出:

ID in main: 1
ID in thread: 1
ID of thread: 2

如果这不是期望的输出,请澄清您的问题
顺便说一句:您的想法似乎是最好的解决方案,因为即使是系统也不会跟踪父线程。是否可以从子线程获取父线程ID?

最新更新