从类内部线程化成员函数

时间:2016-04-27 14:54:21

标签: c++ multithreading class c++11 visual-studio-2015

我试图制作一个多线程初始化例程,根据concurentThreadsSupported的数量来分配任务。它是一个构造函数,调用另一个成员函数,但无论我如何格式化它,我似乎无法将其他成员函数称为线程函数。那么我如何在类中使用参数正确地线程化成员函数呢?

在它被问到之前,我没有使用"使用命名空间std;"而是,我使用"使用std :: vector; "和其他人的要求。

Universe::Universe(const unsigned __int16 & NumberOfStars, const UniverseType & Type, const UniverseAge & Age)
{
    thread *t = new thread[concurentThreadsSupported-1];
    for (unsigned __int32 i = concurentThreadsSupported - 1; i > 0; i--)
    {
        //problem line
        t[i] = thread(&Universe::System_Spawner, i, NumberOfStars / concurentThreadsSupported, Type, Age);
    }
    for (int i = concurentThreadsSupported - 1; i > 0; i--)
    {
        t[i].join();
        cout << "Thread joined" << endl;
    }
    delete[] t;
}

void Universe::System_Spawner(const unsigned __int16 threadNumber, 
const unsigned __int16 NumberOfStars, const UniverseType & Type, const UniverseAge & Age)
{
    cout << "Inside Thread" << endl;
}

我得到的错误是

c:\ program files(x86)\ microsoft visual studio 14.0 \ vc \ include \ thr \ xthread(238):错误C2672:&#39; std :: invoke&#39;:找不到匹配的重载函数

...

c:\ program files(x86)\ microsoft visual studio 14.0 \ vc \ include \ thr \ xthread(238):错误C2893:无法专门化函数模板&#39; unknown-type std :: invoke(_Callable&amp; ;&amp;,_ Types&amp;&amp; ...)&#39;

c:\ program files(x86)\ microsoft visual studio 14.0 \ vc \ include \ thr \ xthread(238):注意:使用以下模板参数:

c:\ program files(x86)\ microsoft visual studio 14.0 \ vc \ include \ thr \ xthread(238):注意:&#39; _Callable = void(__ cdecl Universe :: *)(unsigned short,unsigned short ,const UniverseType&amp;,const UniverseAge&amp;)&#39;

c:\ program files(x86)\ microsoft visual studio 14.0 \ vc \ include \ thr \ xthread(238):注意:&#39; _Types = {unsigned int,unsigned int,UniverseType,UniverseAge}&#39 ;

1 个答案:

答案 0 :(得分:2)

类的所有成员函数都有this作为隐式的第一个参数。通常在调用成员函数时,编译器会为您处理此问题,但在创建std::thread的新实例时,您必须自己执行此操作:

t[i] = thread(&Universe::System_Spawner, this, i, NumberOfStars / concurentThreadsSupported, Type, Age);