我在线程化并将同一个类的多个对象传递给函数时遇到问题。它是一个外部函数,在其中要对每个传递的对象调用类方法。 我尝试传递对象的向量以及指针的向量。我也尝试通过参考传递它们。
指定,我有一个“ Gas”类,其中3个对象是在前面的代码中构造的。我之前在线程中调用过很多方法,所以我猜该类没有问题。 编译器返回很长的错误,即带有_M_invoke(_Index_tuple <_indices ...>)的错误:
.In file included from C:/tdm-gcc-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/thread:39:0,from ./src/../input.h:22,from ./src/mass_source.cpp:12:
C:/tdm-gcc-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/functional: In instantiation of 'struct std::_Bind_simple<void (*(int,std::reference_wrapper<std::vector<Ref::Gas> >))(int,std::vector<Ref::Gas>&)>':
C:/tdm-gcc-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/thread:142:59: required from 'std::thread::thread(_Callable&&,_Args&& ...) [with _Callable = void (&)(int,std::vector<Ref::Gas>&); _Args = {int&,std::reference_wrapper<std::vector<Ref::Gas,std::allocator<Ref::Gas> > >}]'
./src/mass_source.cpp:86:50: required from here
C:/tdm-gcc-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/functional:1505:61: error: no type named 'type' in 'class std::result_of<void (*(int,std::vector<Ref::Gas>&)>'
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
C:/tdm-gcc-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/functional:1526:9: error: no type named 'type' in 'class std::result_of<void (*(int,std::vector<Ref::Gas>&)>'
_M_invoke(_Index_tuple<_Indices...>)
该错误消息来自我的“原始”代码,在其中我注释掉了所有行,以下不再赘述。据报道令人困惑,这里有一个解释:
from ./src/../input.h:22 - inclusion of thread library
from ./src/mass_source.cpp:12: - inclusion of the above input.h file
./src/mass_source.cpp:86: - calc_ms fucntion call
在类声明的下面:
namespace Ref{
class Gas{
public:
Gas(const int id,const int& imax,const int& jmax){
id_ = id;
NX_ = imax;
NR_ = jmax;
}
void set_ms(int m,double& mass_source){
ms_[m] = mass_source;
}
private:
int id_;
int NX_,NR_;
std::vector<double> ms_;
};
} //end of namespace
调用我遇到问题的函数的代码(创建Gas对象及其指针):
using namespace Ref;
void calc_ms(int m,std::vector<Gas>& GAS);
int main(){
int i;
std::vector<Gas> gases;
std::vector<Gas*> ptr_gas(3);
for(i = 0; i < 3; i++){
gases.push_back(Gas(i,grid));
}
for(i = 0; i < 3; i++){
ptr_gas[i] = &gases[i];
}
std::vector<std::thread*> th_gas;
for(i = 0; i < 20; i++){
std::thread *thr = new std::thread(calc_ms,i,std::ref(gases));
th_gas.push_back(thr);
}
for(auto &X : th_gas){
X->join();
delete X;
}
th_gas.clear();
}
以及calc_ms功能定义:
using namespace Ref;
void calc_ms(int m,std::vector<Gas>& GAS){
double MassSourceCH4 = .... ;
double MassSourceCO = .... ;
double MassSourceCO2 = .... ;
GAS[0].set_ms(m,MassSourceCH4);
GAS[1].set_ms(m,MassSourceCO);
GAS[2].set_ms(m,MassSourceCO2);
}
我还尝试过通过副本传递气体,并以ptr_gas作为参考和副本。
注释:Gas类的ms_成员在代码中的其他地方已调整大小,因此使用索引进行赋值不是问题。