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

时间:2016-12-18 21:21:07

标签: 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<< endl;
}

void main() {   
    thread th[NUM_TH];

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

}

我收到错误“无法将参数1从void转换为t”

2 个答案:

答案 0 :(得分:0)

由于这么多原因,它并没有“起作用”。首先确保它编译。其次,线程不像字符串那样简单。你不能复制线程;你只能移动线程。你正在做的是尝试初始化一个“空”线程,然后复制另一个线程。如果你想要一个数组,你可以做的是改为使用指针。要获取当前线程ID,您必须使用this_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();
    }
}

答案 1 :(得分:0)

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

因此,删除参数并改为使用std::thread::id this_id = std::this_thread::get_id();

相关问题