how to get the parent id in c++ with thread?

785 views Asked by At

I want to know how I can get the parent id from a created thread. I had the idea that i make an id variable in the main function and give it as a parameter when i create the thread, but it doesn't work. Or can i get the parent id otherwise?

My code:

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;

}

What are your ideas?

1

There are 1 answers

0
molicious On

The program

#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;
}

generates the output:

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

If this isn't the desired output, please clarify your question.
By the way: Your idea seems to be the best solution, because even the system does not keep track of parent threads. Is it possible to get parent threadID from child?