在用 c++ 编写多线程应用程序时,有必要将大量对向量的引用传递给以多线程模式 (multy) 运行的函数,这些函数对每个线程都有自己的值。编译导致错误:
- 严重性代码说明项目文件行抑制状态错误C2672 'std::invoke': 找不到匹配的重载函数
- 严重性代码描述项目文件行抑制状态错误 C2893 无法专门化函数模板“未知类型 std::invoke(_Callable &&,_Types &&...) noexcept()”
控制台应用程序代码如下:
#include "pch.h"
#include "libraries.h"
#include "globalVariables.h"
//#include "multyThreadingFunc.h"
thread_local double centerOfMass = 0.0;
thread_local double templateZ;
vector<float> distanceAxis(n_bin + 1);
//here the total number of molecules in each bin is saved during the loop for the analyte molecules
vector<double> vectordensity(n_bin);
mutex mtx;
void multy(FILE &fid, int &amountOfAtoms, float &time, vector<float> &coordinates, vector<float> &changedCoord, double ¢erOfMass, double &templateZ, vector<double> &vectordensity) {
FILE *file = &fid;
...//some calculating
}
int main()
{
thread_local vector<float> coordinates(3); //x,y,z coordinates
thread_local vector<double> changedCoord;
FILE *fid = fopen("Benzene_Simu1_0_35ns.gro","rt");
if (fid == NULL) throw exception("Error was happend with the file");
float time;
for (int i = 1; i <= n_bin; i++) {
distanceAxis[i] = (i - 0.5)*BinWidth;
}
int startTime = clock();
while (true) {
std::thread thr(multy, ref(fid), &amountOfAtoms, &time, ref(coordinates), ref(changedCoord), ¢erOfMass, &templateZ, ref(vectordensity));
if (feof(fid)) break;
vectordensity[bin]++; //sorts the molecules according to their bins
//after finishing the loop, density contains the distribution of the molecules over all bins for all time steps
index++;
}
--index;
fclose(fid);
cout << endl << (endTime - startTime) / 1000 << endl;
return 0;
}
向流传递参数时写了一些废话。例如,在流函数中,参数
是对 的引用
int,当你创建一个流时,你会通过那里那些。指向
int. 其他选项也存在此错误。难怪编译器不能调用线程函数。很明显,您正确地传递了对向量的引用,但由于某种原因,您没有传递对标量值的引用。这种划分从何而来?使用参数
fid,发生了一些难以理解的事情。为什么当线程函数需要时它被传递ref(fid)(即实际上) ?它是什么,为什么需要这个?你为什么不马上派一个正常人来?FILE *&FILE &FILE &FILE &FILE *此外,我没有在您的代码中看到任何尝试“对每个线程都有自己的值的向量进行一定数量的引用”。为了让每个线程都有一个向量的“自己的值”,有必要为每个线程创建一个单独的向量实例。但我在任何地方都看不到它。所有线程都接收对相同向量的引用。
thread_local特别是,如果所有线程都从主线程接收到对相同数据的引用并使用它们,则不清楚为什么要在代码中设置这些说明符。