-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix_threads.c
73 lines (63 loc) · 1.41 KB
/
matrix_threads.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#define M 1500
#define P 500
#define N 300
#define NUM_THREADS 4
int matrix1[M][P];
int matrix2[P][N];
int result[M][N];
struct bounds
{
int begin;
int end;
};
void * matrixm(void * arg){
struct bounds *c;
c=(struct bounds*)arg;
for (int i = c->begin; i < c->end; ++i)
{
for(int j=0;j<N;j++){
for(int k=0;k<P;k++){
result[i][j]+=matrix1[i][k]*matrix2[k][j];
}
}
}
pthread_exit(NULL);
}
int main()
{
int i, j, k;
for (i = 0; i < M; i++) {
for (j = 0; j < P; j++) {
matrix1[i][j] = i + j;
}
}
for (i = 0; i < P; i++) {
for (j = 0; j < N; j++) {
matrix2[i][j] = i - j;
}
}
clock_t start = clock();
pthread_t threads[NUM_THREADS];
struct bounds c[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i)
{
c[i].begin=i*M/NUM_THREADS;
c[i].end=c[i].begin+M/NUM_THREADS;
if(i==NUM_THREADS-1){
c[i].end=M;
}
pthread_create(&threads[i],NULL,matrixm,(void*)&c[i]);
}
for (int i = 0; i < NUM_THREADS; ++i)
{
pthread_join(threads[i],NULL);
}
clock_t end = clock();
double time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken: %f seconds\n", time_taken);
pthread_exit(NULL);
return 0;
}