在用C++多线程运算矩阵相乘的时候,出现了一些状况。
#include <iostream>
#include <cstdlib>
#include <windows.h>
using namespace std;
struct v {
int i;
int j;
};
int m, k, n;
int a[100][100];
int b[100][100];
int c[100][100];
DWORD WINAPI Fun1Proc(v* mm) {
if (mm->i == -1) return 0;
int sum = 0;
for (int i = 0; i < k; i++) {
sum += a[mm->i][i] * b[i][mm->j];
}
c[mm->i][mm->j] = sum;
return 0;
}
int main() {
cin >> m >> k >> n;
for (int i = 0;i < m;i++) {
for (int j = 0;j < k;j++) {
cin >> a[i][j];
}
}
for (int i = 0;i < k;i++) {
for (int j = 0;j < n;j++) {
cin >> b[i][j];
}
}
//v *p = new v;
//p->i = -1;
//p->j = 0;
//HANDLE handle_1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Fun1Proc, p, 0, NULL);
//HANDLE handle_2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Fun1Proc, p, 0, NULL);
for (int i = 0;i < m;i++) {
for (int j = 0;j < n;j++) {
v *threadPara = new v;
threadPara->i = i;
threadPara->j = j;
HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Fun1Proc, threadPara, 0, NULL);
CloseHandle(handle);
}
}
for (int i = 0;i < m;i++) {
for (int j = 0;j < n;j++) {
cout << c[i][j] << " ";
}
cout << endl;
}
}
其中片段:
for (int i = 0;i < m;i++) {
for (int j = 0;j < n;j++) {
v *threadPara = new v; // 此处改成v threadPara; 会出现问题。 前面几个线程莫名其妙的没有运行下去。
threadPara->i = i;
threadPara->j = j;
HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Fun1Proc, threadPara, 0, NULL);
CloseHandle(handle);
}
}
错误的结果是这样的: