0

我正在做一个涉及使用winthreads乘以矩阵的作业。

我是 C 的新手,这就是我拥有的所有代码(我在这里阅读了一些线程)。

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define M 3
#define K 3
#define N 3
#define NUMBER_OF_THREADS 9

int A[M][K] = { {1,4,3}, {2,5,4}, {3,6,1} }; 
int B[K][N] = { {8,7,6}, {5,4,3}, {7,3,1} };
int C[M][N];

clock_t start,end;


struct v
{
    int i; 
    int j; 
}; 


DWORD WINAPI MatrixMult(LPVOID Param)
{
    int a;

    DWORD sum = 0;

    struct v *data = Param;

    for(a = 0; a < 3; a++)
    {
        sum = sum + ((A[data->i][a]) * (B[a][data->j]));
    }

    C[data->i][data->j] = sum;
    return 0;

}

int main()
{   
    struct v *data = malloc(sizeof(struct v));
    int i, j, k;

    DWORD ThreadIds[NUMBER_OF_THREADS];

    HANDLE ThreadHandles[NUMBER_OF_THREADS];

    int thread_index = 0;

    start = clock();

    for (i = 0; i < M; i++)
    {
        for (j = 0; j < N; j++ )
        {
            data->i = i;
            data->j = j;

            ThreadHandles[thread_index] = CreateThread (NULL, 0, MatrixMult, &data, 0, &ThreadIds[thread_index]);

            if (!ThreadHandles)
            {
                printf("Error, threads cannot be created");
                return 1;
            }
        }

        thread_index++;

    }

    printf("Result:\n");

    for (i = 0; i < M; i++)
    {
        for (j = 0; j < N; j++)
        {
            printf("C[%d][%d] = %f\n", i,j, C[i][j]);
        }
    }

    for (i = 0; i < 9; i++)
    {
        CloseHandle(ThreadHandles[i]);
    }

    end = clock();
    printf("Tiempo = %d", end - start);

    return 0;
}

我在使用这个程序时遇到了一些问题,它可以编译,但没有运行,它标志着 0x775f15de 异常中的错误,读取 0x3468a3bc 时出错。任何想法为什么会出现此错误以及如何解决?

4

1 回答 1

2

There are (at least) three problems:

  1. data is a struct v* but it's address is being passed as the argument to the thread (i.e. a struct v**) which is then being interpreted as a struct v*. This is incorrect and is a probable cause of the error.

  2. All threads will be executing on the same instance of struct v named data. This will introduce race conditions. Allocate a new struct v for each thread and have the thread free() it when no longer required.

  3. The type of C[i][j] is an int but the printf() has the format specifier %f. This is incorrect, it should be %d (as it is for the other arguments).

Note that it is not required to cast the return value of malloc()( Do I cast the result of malloc? ). A more common and better way of writing the malloc() line from the posted code is:

struct v* data = malloc(sizeof(*data));

Remember to free() what is malloc()d.

于 2012-11-16T22:12:02.783 回答