【问题标题】:Threading a member function from inside a class从类内部线程化成员函数
【发布时间】:2016-08-21 23:13:06
【问题描述】:

我正在尝试创建一个多线程初始化例程,该例程将根据 concurentThreadsSupported 的数量划分任务。这是一个调用另一个成员函数的构造函数,但无论我如何格式化它,我似乎都无法将另一个成员函数调用为线程函数。那么我将如何从一个类内部正确地线程化一个带有参数的成员函数呢?

在被问到之前,我没有使用“using namespace std;”,而是使用“using 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): error C2672: 'std::invoke': 找不到匹配的重载函数

...

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

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): 注意:'_Callable=void (__cdecl Universe::* )(unsigned short,unsigned short,const UniverseType &,const UniverseAge &)'

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!你不会想知道我花了多长时间才找到这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多