-
Matrix Problem
Can someone please help!!! I am trying to finish an assignment, I need to write code to do the matrix problem, BUT each time in a seperate thread. This must use Win32 version. What I have so far doesnt seem to work... any help would be soooo appreciated! I have this so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
/* calculate a matrix, create a pointer */
void matrix(int **a){
int i;
int j;
for (i = 0; i < 6; i++){
for (j = 0; j < 6; j++){
printf("%d", a[i][j]);
}
printf("\n");
}
};
int main(){
DWORD ThreadId;
HANDLE ThreadHandle;
int Param;
int i;
int j;
int **a; //pointer
/* allocate memory for 6x6 matrix */
a=(int**)malloc(6*sizeof(int*));
/* while criteria is met for 6x6 matrix*/
for (i = 0; i < 6; i++){
for (j = 0; j < 6; j++){
ThreadHandle = CreateThread(NULL, 0, matrix, &Param, 0, &ThreadId);
if (ThreadHandle != NULL) {
WaitForSingleObject(ThreadHandle, INFINITE);
CloseHandle(ThreadHandle);
}
a=(int**)malloc(6*sizeof(int*));
a[i][j] = i;
}
}
}
-
1. You should decide what you do in the main thread, what in the child
2. You should write for yourself the order of actions in the main thread
3. You should decide what are you passing to the child thread to process the data
My suggestions
- to simplify the start - change the dynamic array to static, when your code will work ok with static matrix - add the memory allocations
- initialize array before you start the thread, using loops
- start the thread outside the loop
-
>int **a; //pointer
That's classic. :)
>a=(int**)malloc(6*sizeof(int*));
A much better way is:
Code:
a = malloc ( 6 * sizeof *a );
But that doesn't allocate enough memory. It just allocates the memory for an array of 6 pointers. To finish the matrix, you need to loop through each pointer and allocate the second dimension:
Code:
a = malloc ( 6 * sizeof *a );
for ( i = 0; i < 6; i++ )
a[i] = malloc ( 6 * sizeof *a[i] );
Then of course you need to free the memory when you're done, but your threads are working with uninitialized data, which is undefined behavior. You need to initialize the matrix before printing it.
>What I have so far doesnt seem to work...
Riiiight. Can you be more specific? You don't go to a doctor and expect him to fix you up after saying "it hurts", do you?
Here's a tip: Get your code to work before adding threads. It'll save you a lot of headaches.