各スレッドが単一の乗算を実行し、メインスレッドがすべての結果を合計して、最終的なマトリックスの適切な場所に配置するスレッドを使用して行列乗算を実行しようとしています(他のスレッドが終了した後)。
私がやろうとしている方法は、各スレッドの結果を保持する単一の行配列を作成することです。次に、配列を調べて、結果を追加して最終的な行列に配置します。
例:行列がある場合:
A = [{1,4}、{2,5}、{3,6}] B = [{8,7,6}、{5,4,3}]
次に、[8、20、7、16、6、12、16など]を保持する配列が必要です。次に、配列をループして2つの数値を合計し、それらを最終的な配列に配置します。
これはHW割り当てであるため、正確なコードは探していませんが、結果を配列に適切に格納する方法に関するロジックを探しています。数字を見逃さないように、各マトリックスのどこにいるかを追跡する方法に苦労しています。
ありがとう。
EDIT2:実行されるすべての単一の乗算に対して単一のスレッドが必要であることを言及するのを忘れました。上記の例の意味では、それぞれが独自の計算を行う18のスレッドがあります。
編集:私は現在、このコードをベースとして使用しています。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define M 3
#define K 2
#define N 3
#define NUM_THREADS 10
int A [M][K] = { {1,4}, {2,5}, {3,6} };
int B [K][N] = { {8,7,6}, {5,4,3} };
int C [M][N];
struct v {
int i; /* row */
int j; /* column */
};
void *runner(void *param); /* the thread */
int main(int argc, char *argv[]) {
int i,j, count = 0;
for(i = 0; i < M; i++) {
for(j = 0; j < N; j++) {
//Assign a row and column for each thread
struct v *data = (struct v *) malloc(sizeof(struct v));
data->i = i;
data->j = j;
/* Now create the thread passing it data as a parameter */
pthread_t tid; //Thread ID
pthread_attr_t attr; //Set of thread attributes
//Get the default attributes
pthread_attr_init(&attr);
//Create the thread
pthread_create(&tid,&attr,runner,data);
//Make sure the parent waits for all thread to complete
pthread_join(tid, NULL);
count++;
}
}
//Print out the resulting matrix
for(i = 0; i < M; i++) {
for(j = 0; j < N; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
}
//The thread will begin control in this function
void *runner(void *param) {
struct v *data = param; // the structure that holds our data
int n, sum = 0; //the counter and sum
//Row multiplied by column
for(n = 0; n< K; n++){
sum += A[data->i][n] * B[n][data->j];
}
//assign the sum to its coordinate
C[data->i][data->j] = sum;
//Exit the thread
pthread_exit(0);
}
ソース: http: //macboypro.wordpress.com/2009/05/20/matrix-multiplication-in-c-using-pthreads-on-linux/