1. 程式人生 > >win32 多執行緒的問題(未解決)

win32 多執行緒的問題(未解決)

在用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);
		}
	}

錯誤的結果是這樣的: