C++ 线程矩阵乘法函数
我试图写两个矩阵乘法函数,一个是标准的,另一个是线程的。但是,我不知道如何正确调用线程函数 代码如下:C++ 线程矩阵乘法函数,c++,multithreading,matrix-multiplication,C++,Multithreading,Matrix Multiplication,我试图写两个矩阵乘法函数,一个是标准的,另一个是线程的。但是,我不知道如何正确调用线程函数 代码如下: #include <iostream> #include <future> #include <sys/time.h> #include <stdio.h> #include <thread> using namespace std; double get_wallTime() { struct timeval tp;
#include <iostream>
#include <future>
#include <sys/time.h>
#include <stdio.h>
#include <thread>
using namespace std;
double get_wallTime() {
struct timeval tp;
gettimeofday(&tp, NULL);
return (double) (tp.tv_sec + tp.tv_usec/1000000.0);
}
static void matrixMultiply(double** a, double** b, double** product, int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
product[i][j] += a[i][k] * b[k][j];
}
}
}
}
static void matrixMultiplyThreaded(double** a, double** b, double** product, int dimLower, int dimUpper, int dim) {
for (int i = dimLower; i < dimUpper; i++) {
for (int j = 0; j < dim; j++) {
for (int k = 0; k < dim; k++) {
product[i][j] += a[i][k] * b[k][j];
}
}
}
}
int main(int argc, char *argv[]) {
if (argc < 3) {
cout << "Not enough arguments.";
}
int numTimes = atoi(argv[1]);
char *threadOrNo = argv[2];
int size = atoi(argv[3]);
double a[size][size], b[size][size] = {};
double product[size][size] = {};
for (int i=0; i<size; i++) {
for (int j=0; j < size; j++) {
a[i][j] = 2;
b[i][j] = 3;
}
}
double t1 = get_wallTime();
if (*threadOrNo == 'y') {
int dim1 = size / 2;
for (int n = 0; n < numTimes; n++) {
std::thread first (matrixMultiplyThreaded, a, b, product, 0, dim1, size);
std::thread second (matrixMultiplyThreaded, a, b, product, dim1, size, size);
first.join();
second.join();
}
}
else {
for (int m = 0; m < numTimes; m++) {
matrixMultiply(a[size][size],b[size][size], product[size][size], size);
}
}
double t2 = get_wallTime();
double totalTime = t2 - t1;
cout << "time : " << totalTime;
}
由于其他错误,我无法编译您的代码,但是对于启动线程的部分,您应该使用lambdas:
std::thread first([=]() { matrixMultiplyThreaded(a, b, product, 0, dim1, size); });
std::thread second([=]() { matrixMultiplyThreaded(a, b, product, dim1, size, size); });
除其他错误外,您不能使用变量(动态值)静态分配数组(a
、b
和product
)。按以下步骤进行:
double **a = new double*[size];
double **b = new double*[size];
double **product = new double*[size];
for (int i = 0; i < size; i++)
{
a[i] = new double[size];
b[i] = new double[size];
product[i] = new double[size];
}
由于其他错误,我无法编译您的代码,但是对于启动线程的部分,您应该使用lambdas:
std::thread first([=]() { matrixMultiplyThreaded(a, b, product, 0, dim1, size); });
std::thread second([=]() { matrixMultiplyThreaded(a, b, product, dim1, size, size); });
除其他错误外,您不能使用变量(动态值)静态分配数组(a
、b
和product
)。按以下步骤进行:
double **a = new double*[size];
double **b = new double*[size];
double **product = new double*[size];
for (int i = 0; i < size; i++)
{
a[i] = new double[size];
b[i] = new double[size];
product[i] = new double[size];
}
您需要在这里添加线程,或者这只是一个练习?(参见第6.2.1节)这里需要线程,或者这只是一个练习?(见第6.2.1节)