我正在尝试通过执行多线程矩阵乘法程序来学习多线程。我一次计算一行。当我使用的线程数少于行数时,我遇到了问题。我阅读了很多类似的帖子,但无法清楚地理解如何重用它们。但是有两种可能的方法。
使用线程池并创建任务队列-任务完成后我不明白下一个任务如何分配给线程池中的特定线程
消息队列。
如何在共享变量 sum 上使用互斥锁?
请建议我应该在以下程序中添加的可能更改。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define M 6
#define K 7
#define N 8
#define NUM_THREADS 4
int A[M][K] = { { 1, 4, 8, 4, 5, 6, 2 }, { 7, 3, 2, 4, 1, 4, 5 }, { 2, 3, 9, 4,
7, 1, 5 }, { 4, 3, 9, 4, 7, 2, 5 }, { 1, 3, 9, 9, 7, 1, 3 }, { 2, 4, 9,
3, 7, 1, 5 } };
int B[K][N] = { { 8, 3, 8, 4, 5, 6, 2, 3 }, { 1, 3, 2, 2, 3, 4, 8, 1 }, { 8, 3,
9, 1, 7, 1, 5, 2 }, { 1, 3, 9, 2, 7, 2, 5, 2 },
{ 1, 3, 9, 2, 7, 1, 3, 3 }, { 2, 4, 9, 3, 7, 1, 5, 2 }, { 2, 4, 9, 3, 7,
1, 5, 2 } };
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 < NUM_THREADS; i++) {
//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[NUM_THREADS]; //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, x, sum = 0; //the counter and sum
//Calculating one row
for (x = 0; x < N; x++) {
for (n = 0; n < K; n++)
{
sum += A[data->i][n] * B[n][x];
}
//assign the sum to its coordinate
C[data->i][data->j] = sum;
}
//Exit the thread
pthread_exit(0); // How can I reuse this thread for another row instead of exiting it ?
}
任何帮助将不胜感激!