![](/img/trans.png)
[英]Is it possible from within a thread in C/C++ to get a parent thread id if it wasn't passed in as an argument on pthread_create?
[英]how to get the parent id in c++ with thread?
我想知道如何从创建的线程中获取父 ID。 我的想法是在主 function 中创建一个 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;
}
生成 output:
ID in main: 1
ID in thread: 1
ID of thread: 2
如果这不是所需的 output,请澄清您的问题。
顺便说一句:您的想法似乎是最好的解决方案,因为即使系统也不跟踪父线程。 是否可以从孩子那里获取父线程ID?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.