如何使用线程在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

如果这不是所需的输出,请澄清您的问题。
顺便说一句:您的想法似乎是最好的解决方案,因为即使系统也不会跟踪父线程。 Is it possible to get parent threadID from child?