|
| 1 | +/* |
| 2 | +Simple example of a huge matrix multiplication |
| 3 | +and speeding the process up as much as possible |
| 4 | +by running the main tasks parallelly using threads |
| 5 | +*/ |
| 6 | + |
| 7 | +#include <stdio.h> |
| 8 | +#include <stdlib.h> |
| 9 | +#include <pthread.h> |
| 10 | +#define SIZE 1024 |
| 11 | + |
| 12 | +static double a[SIZE][SIZE]; |
| 13 | +static double b[SIZE][SIZE]; |
| 14 | +static double c[SIZE][SIZE]; |
| 15 | + |
| 16 | +void *initialize_row(void *arg) { |
| 17 | + int row = *(int *)arg; |
| 18 | + free(arg); |
| 19 | + |
| 20 | + for (int j = 0; j < SIZE; j++) { |
| 21 | + a[row][j] = 1.0; |
| 22 | + b[row][j] = 1.0; |
| 23 | + } |
| 24 | + return NULL; |
| 25 | +} |
| 26 | + |
| 27 | +static void init_matrix() { |
| 28 | + pthread_t threads[SIZE]; |
| 29 | + |
| 30 | + for (int i = 0; i < SIZE; i++) { |
| 31 | + int *row = malloc(sizeof(int)); |
| 32 | + *row = i; |
| 33 | + |
| 34 | + pthread_create(&threads[i], NULL, initialize_row, row); |
| 35 | + } |
| 36 | + |
| 37 | + for (int i = 0; i < SIZE; i++) { |
| 38 | + pthread_join(threads[i], NULL); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | +static void |
| 44 | +print_matrix(void) |
| 45 | +{ |
| 46 | + int i, j; |
| 47 | + |
| 48 | + for (i = 0; i < SIZE; i++) { |
| 49 | + for (j = 0; j < SIZE; j++) |
| 50 | + printf(" %7.2f", c[i][j]); |
| 51 | + printf("\n"); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +// using the pthread to make it run parallel |
| 57 | +void *matmul_rows(void *arg) { |
| 58 | + int row = *(int *)arg; |
| 59 | + free(arg); |
| 60 | + |
| 61 | + for (int j = 0; j < SIZE; j++) { |
| 62 | + c[row][j] = 0.0; |
| 63 | + for (int k = 0; k < SIZE; k++) { |
| 64 | + c[row][j] += a[row][k] * b[k][j]; |
| 65 | + } |
| 66 | + } |
| 67 | + return NULL; |
| 68 | +} |
| 69 | + |
| 70 | +static void matmul_para() { |
| 71 | + pthread_t threads[SIZE]; |
| 72 | + |
| 73 | + for (int i = 0; i < SIZE; i++) { |
| 74 | + int *row = malloc(sizeof(int)); |
| 75 | + *row = i; |
| 76 | + |
| 77 | + pthread_create(&threads[i], NULL, matmul_rows, row); |
| 78 | + } |
| 79 | + |
| 80 | + for (int i = 0; i < SIZE; i++) { |
| 81 | + pthread_join(threads[i], NULL); |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | + |
| 86 | +int |
| 87 | +main(int argc, char **argv) |
| 88 | +{ |
| 89 | + init_matrix(); |
| 90 | + matmul_para(); |
| 91 | + print_matrix(); |
| 92 | +} |
0 commit comments