Save the following lines of code in a file called matrix_multiplication.c, then compile and run it:
1 2 |
$ gcc -o matrix_multiplication matrix_multiplication.c -lpthread $ ./matrix_multiplication |
I would recommend running in parallel the top command in another shell window to observe the system/processors load.
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 |
#include <pthread.h> #include <stdio.h> #include <time.h> // use 4 for a quad processor, but try also with 1 and 2 threads // to check the running time and the system load #define thread_count 4 // matrix dimension #define dim 1500 struct param { int start_line, end_line; }; int a[dim][dim], b[dim][dim], c[dim][dim]; void init_matrix(int m[dim][dim]) { int i, j; for (i = 0; i < dim; i++) for (j = 0; j < dim; j++) m[i][j] = random() % 100; } void* thread_function(void *v) { struct param *p = (struct param *) v; int i, j, k; for (i = p->start_line; i < p->end_line; i++) for (j = 0; j < dim; j++) { int s = 0; for (k = 0; k < dim; k++) s += a[i][k] * b[k][j]; c[i][j] = s; } } int main() { int i; struct param params[thread_count]; pthread_t t[thread_count]; srand(getpid()); int start_time, end_time; init_matrix(a); init_matrix(b); start_time = time(NULL); for (i = 0; i < thread_count; i++) { int code; params[i].start_line = i * (dim / thread_count); params[i].end_line = (i + 1) * (dim / thread_count); code = pthread_create(&t[i], NULL, thread_function, ¶ms[i]); if (code != 0) printf("Error starting thread %d\n", i); } for (i = 0; i < thread_count; i++) pthread_join(t[i], NULL); end_time = time(NULL); printf("Running time: %d\n", end_time - start_time); } |