【发布时间】:2010-06-06 22:29:35
【问题描述】:
所以我一直在玩 pthreads,特别是试图计算两个矩阵的乘积。我的代码非常混乱,因为它只是对我自己来说是一个快速有趣的项目,但我使用的线程理论非常相似:
#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.com/blog/2009/06/29/matrix-multiplication-in-c-using-pthreads-on-linux/
对于非线程版本,我使用了相同的设置(3 个二维矩阵,动态分配的结构来保存 r/c),并添加了一个计时器。第一次试验表明非线程版本更快。我的第一个想法是尺寸太小而无法注意到差异,并且创建线程需要更长的时间。所以我将尺寸提高到大约 50x50,随机填充并运行它,但我仍然没有看到线程版本的任何性能提升。
我在这里错过了什么?
【问题讨论】:
-
您在哪种处理器上运行它?如果它不是多线程或双核,您将看不到使用多线程的任何优势。事实上,为了同时运行两个线程而必须进行的上下文切换实际上会损害性能。
-
50x50 矩阵对于现代计算机来说仍然太小。如果您正在寻找性能问题,您将不得不转向更大的尺寸——数万行和数万列。那么寻找优化(例如多线程)是有意义的。
标签: c multithreading