[英]Matrix Multiplication Using win32 threads
我不知道我的代碼有什么問題。它總是在所有元素中返回零。 提示問題出在哪里會很棒:)
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int nGlobalCount = 0;
int thread_index = 0;
int num_of_thr=5;
int a[4][4], b[4][4], c[4][4];
int i, j, k;
struct v {
int i; /*row*/
int j; /*column*/
};
DWORD ThreadProc (LPVOID lpdwThreadParam ) {
//
struct v *input = (struct v *)lpdwThreadParam;
int avg=4*4/num_of_thr;
int count=0;
for(int i = 0; i <= 3 ; i++) {
for(int j = 0; j <= 3; j++) {
int sum=0;
for ( k = 0 ; k <= 3; k++) {
sum=sum+((a[input->i][k])*(b[k][input->j]));
c[input->i][input->j]=sum;
count++;
}
}
}
//Print Thread Number
//printf ("Thread #: %d\n", *((int*)lpdwThreadParam));
//Reduce the count
return 0;
}
int main() {
// int x=0;
cout<<"enter no of threads : ";
cin>>num_of_thr;
DWORD ThreadIds[num_of_thr];
HANDLE ThreadHandles[num_of_thr];
//struct v {
// int i; /*row*/
// int j; /*column*/
//};
struct v data[num_of_thr];
int i , j , k;
for ( int i = 0 ; i <= 3; i++) {
for (int j = 0 ; j <= 3 ; j++) {
a[i][j] = rand() % 10;
b[i][j] = rand() % 10;
c[i][j] = 0;
}
}
for(int i = 0; i < num_of_thr/2; i++) {
for(int j = 0; j < num_of_thr/2; j++) {
data[thread_index].i = i;
data[thread_index].j = j;
ThreadHandles[thread_index] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadProc, &data[thread_index], 0,&ThreadIds[thread_index]);
thread_index++;
}
}
WaitForMultipleObjects(num_of_thr, ThreadHandles, TRUE, INFINITE);
cout<<"The resultant matrix is "<<endl;
for ( i = 0 ; i < 4; i++) {
for ( j = 0 ; j < 4 ; j++)
cout<<c[i][j]<<" ";
cout<<endl;
}
for (int i=0; i<num_of_thr; i++)
CloseHandle(ThreadHandles[i]);
return 0;
}
乍一看,循環中的總和聲明看起來很粗略。
for(int i = 0; i <= 3 ; i++) {
for(int j = 0; j <= 3; j++) {
for ( k = 0 ; k <= 3; k++)
{
int sum=sum+((a[input->i][k])*(b[k][input->j])); // this declaration seems wrong
c[input->i][input->j]=sum;
count++;
}
}
}
您重新聲明總和的每個內部循環將其有效地設為0。您可能要根據所要實現的目標,將聲明從分配中向上移動一或兩個循環。
您是否意識到您有兩組分別名為a,b和c的變量? 一個是函數main的局部變量,另一個是整個程序的靜態變量。 我懷疑這不是您想要的。 嘗試刪除對main本地的一個。
馬丁
除了前面提到的其他問題外,我在尋找的同時發現了一些其他東西:
DWORD ThreadIds[num_of_thr];
具有非恆定數組大小的數組聲明(我只是將num_of_thr
為常量,並注釋掉了cin
以對其進行快速測試)。 cin >> num_of_thr;
例如,如果num_of_thr
為0,這將解釋零輸出。 一個簡單的cout
這里num_of_thr
將是有益的。 for(int i = 0; i < num_of_thr/2; i++) {
開頭的數據初始化循環中, for(int i = 0; i < num_of_thr/2; i++) {
您沒有正確計數線程,這將導致數組下溢或溢出。 例如,如果num_of_thr
為5,則num_of_thr/2
為2,這導致僅初始化元素0..3,而最后一個元素未初始化。 從技術上講,數組下溢是可以的,盡管稍后的CloseHandle()
調用在嘗試釋放本質上隨機的句柄時將失敗。 如果輸入更多線程,則將使所有數組溢出(例如,以num_of_thr=10
嘗試)。 ThreadProc()
函數,而不是從線程內部調用。 使用調試器跟蹤程序或將日志輸出到stdout / file(在線程模型中也可以使用)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.