1
我想寫兩個矩陣乘法函數,一個標準和一個線程。但是,我不知道如何正確調用線程函數。螺紋矩陣乘法函數
下面是代碼:
#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;
}
如果任何人都可以給任何意見,我將永遠感激。具體來說,爲線程函數實現線程的正確方法是什麼?
這是第一個錯誤消息我收到,我一直試圖解決好幾次:
multiplyMatrix.cpp: In function 'int main(int, char**)':
multiplyMatrix.cpp:64:82: error: no matching function for call to 'std::thread::thread(void (&)(double**, double**, double**, int, int, int), double [size][size], double [size][size], double [size][size], int, int&, int&)'
std::thread first (matrixMultiplyThreaded, a, b, product, 0, dim1, size);
[確定](http://lwn.net/Articles/255364/),你需要線程[提高性能](http://lwn.net/Articles/258188/)在這裏,還是隻是一個練習? (見6.2.1節) – tweej