chundoong-lab-ta/SamsungDS22/submissions/HW2/juwon76.seo/mat_mul.cpp

60 lines
1.1 KiB
C++

#include "mat_mul.h"
#include <cstdlib>
#include <cstdio>
#include <pthread.h>
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
#define BS 40
#define MIN(a,b) ((a>b) ? b : a)
static void* mat_mul_thread(void *data) {
int pid = * (int *) data;
int slice = M / num_threads;
int start = pid * slice;
int end = pid == num_threads - 1 ? M : (pid + 1) * slice;
int kk,i,j,k;
float Aik;
for (kk = 0; kk < K; kk += BS){
for (i = start; i < end; i++){
for (k = kk; k < MIN(kk+BS, K); k++)
{
Aik = A[i * K + k];
for (j = 0; j < N; j++){
C[i * N + j] += Aik * B[k * N + j];
}
}
}
}
return NULL;
}
void mat_mul(float *_A, float *_B, float *_C, int _M, int _N, int _K, int _num_threads) {
A = _A, B = _B, C = _C;
M = _M, N = _N, K = _K;
num_threads = _num_threads;
// TODO: create '_num_threads' pthreads
pthread_t thread[40];
int pid[40];
for (int i = 0; i < num_threads; i++) {
pid[i] = i;
pthread_create(&thread[i], NULL, mat_mul_thread, &pid[i]);
}
for (int i = 0; i < num_threads; i++) {
pthread_join(thread[i], NULL);
}
}