gpt4 book ai didi

c++ - 使用 win32 线程的矩阵乘法

转载 作者:搜寻专家 更新时间:2023-10-31 00:45:49 25 4
gpt4 key购买 nike

我不知道我的代码有什么问题……它总是在所有元素中返回零。提示问题出在哪里会很棒 :)

#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;
}

最佳答案

乍看之下,您在循环中的 sum 声明看起来很粗略。

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。您可能希望将声明从赋值向上移动一个或两个循环,具体取决于您要实现的目标。

关于c++ - 使用 win32 线程的矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com