【问题标题】:how to get the parent id in c++ with thread?如何使用线程在 C++ 中获取父 ID?
【发布时间】:2021-08-14 10:53:11
【问题描述】:

我想知道如何从创建的线程中获取父 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;

}

你有什么想法?

【问题讨论】:

  • 为什么这段代码不起作用?
  • 你必须在程序终止之前加入你的线程,thread.join();return 0; 语句之前。

标签: c++ multithreading parent parentid


【解决方案1】:

程序

#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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2014-02-01
    • 2010-10-29
    相关资源
    最近更新 更多