C++ 如何在线程中运行的函数中获取当前线程id?

C++ 如何在线程中运行的函数中获取当前线程id?,c++,C++,如何在线程上运行的函数中获取当前线程ID? 我试过这样做,但没用 #include <thread> #include <iostream> using namespace std; #define NUM_TH 4 void printhello(thread t) { auto th_id = t.get_id(); cout << "Hello world! Thread ID, "<<th_id<< en

如何在线程上运行的函数中获取当前线程ID? 我试过这样做,但没用

#include <thread>
#include <iostream>

using namespace std;

#define NUM_TH 4

void printhello(thread t) { 
    auto th_id = t.get_id();
    cout << "Hello world! Thread ID, "<<th_id<< endl;
}

void main() {   
    thread th[NUM_TH];

    for (int i = 0; i < NUM_TH; i++) {
        th[i]=thread(printhello,th[i]); 
        th[i].join();
    }

}
#包括
#包括
使用名称空间std;
#定义第4个数字
void printhello(线程t){
自动th_id=t.get_id();
cout由于很多原因,它无法“工作”。首先,确保它能够编译。其次,线程不像字符串那样是简单的类。您不能复制线程,只能移动线程。您正在做的是尝试初始化“空”线程线程,然后在其上复制另一个线程。如果需要数组,可以使用指针。要获取当前线程id,必须使用以下线程::get_id()

#包括
#包括
#定义第4个数字
使用名称空间std;
void printhello(){
自动线程id=此线程::获取线程id();

cout您可以通过
std::this_thread
访问
printhello的执行线程,而不是将线程传递给函数


因此,请删除该参数并改用
std::thread::id this\u id=std::this\u thread::get\u id();

不起作用有点…模糊。它是否编译?它是否运行时没有错误?它是否只是给出了错误的结果?传递
th[1]时请更具体一点
对于
线程
构造函数,它尚未初始化;也就是说,它是一个空白的、无效的
线程
对象,而不是运行
printhello
的对象。欢迎使用Stack Exchange。您是否阅读了该指南,特别是“如何提出一个好问题”?您正在被投票否决并投票关闭,因为您没有告诉我们实际的问题是什么。请回答这个问题,以便我们可以帮助您。(您还应该在您的邮件中包含您需要的所有标题)您可能正在寻找
std::this_thread::get_id()
?谢谢Igor Tandetnik此_thread::get_id()是我正在寻找的:)
#include <thread>
#include <iostream>

#define NUM_TH 4

using namespace std;

void printhello() { 
    auto th_id = this_thread::get_id();
    cout << "Hello world! Thread ID, "<< th_id << endl;
}

int main() {   
    thread* th[NUM_TH];

    for (int i = 0; i < NUM_TH; i++)
    {
        th[i] = new thread(printhello);
        th[i]->join();
    }
}