2016-04-27 47 views
0

我正在尝试做一个基于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)的\微软的Visual Studio 14.0 \ VC \包括\ THR \ xthread(238):错误C2672:“的std ::调用“:没有匹配的重载函数发现

...

C:\ Program Files文件(x86)的\微软的Visual Studio 14.0 \ VC \包括\ THR \ xthread(238):错误C2893:无法专注功能模板'未知类型std :: invoke(_Callable & &,_类型& & ...)”

C:\ Program Files文件(x86)的\微软的Visual Studio 14.0 \ VC \包括\ THR \ xthread(238):注:与下面的模板参数:

C: \ program files(x86)\ microsoft visual studio 14.0 \ vc \ include \ thr \ xthread(238):note:'_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):note:'_Types = {unsigned int,unsigned int,UniverseType,UniverseAge}'

回答

2

一个类的所有成员函数都有this作为隐含的第一个参数。调用一个成员函数一般当编译器会处理这个给你,但创造的std::thread一个新实例时,必须自己做:

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

谢谢!你不想知道我多久努力找出答案。 – ChrisPy