Last active
November 24, 2020 13:52
-
-
Save auriza/8120103 to your computer and use it in GitHub Desktop.
Matrix addition using multithreading.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <pthread.h> | |
#define T 2 | |
#define N 4 | |
int A[N][N] = {{1,0,1,0},{0,1,1,0},{1,0,1,0},{0,1,1,0}}; | |
int B[N][N] = {{0,2,2,0},{2,0,2,0},{0,2,2,0},{2,0,2,0}}; | |
int C[N][N] = {{0}}; | |
void *matrix_add(void *arg) { | |
int id = *(int*)arg; | |
int i, j; | |
for (i = id; i < N; i += T) | |
for (j = 0; j < N; j++) | |
C[i][j] = A[i][j] + B[i][j]; | |
pthread_exit(NULL); | |
} | |
int main() | |
{ | |
pthread_t thread[T]; | |
int tid[T]; | |
int i, j; | |
for (i = 0; i < T; i++) { | |
tid[i] = i; | |
pthread_create(&thread[i], NULL, matrix_add, &tid[i]); | |
} | |
for (i = 0; i < T; i++) | |
pthread_join(thread[i], NULL); | |
for (i = 0; i < N; i++) | |
for (j = 0; j < N; j++) | |
printf((j < N-1) ? "%d " : "%d\n", C[i][j]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sir how to solve it