chundoong-lab-ta/SamsungDS22/submissions/HW2/sk0812.min/mat_mul.cpp

68 lines
1.5 KiB
C++

#include "mat_mul.h"
#include <cstdlib>
#include <cstdio>
#include <pthread.h>
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
struct thread_info{
int start;
int end;
};
static void* mat_mul_thread(void* data) {
// TODO: parallelize & optimize matrix multiplication
thread_info tInfo = *(thread_info*) data;
float Aik;
int bs = 32;
for (int kk = 0; kk < K; kk += bs) {
for (int i = tInfo.start; i < tInfo.end; ++i) {
for (int k = kk; k < min(kk + bs, K); ++k) {
Aik = A[i * K + k];
for (int 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;
pthread_t threads[40];
thread_info* pThread[40];
// TODO: create '_num_threads' pthreads
for(int idx=0;idx<num_threads;idx++)
{
pThread[idx] = (thread_info *) malloc(sizeof(thread_info));
int slice = M / num_threads;
pThread[idx]->start = idx * slice;
pThread[idx]->end = idx == num_threads - 1 ? M : (idx + 1) * slice;
pthread_create(&threads[idx], NULL, mat_mul_thread, pThread[idx]);
}
for (int idx = 0; idx < num_threads; idx++)
pthread_join(threads[idx], NULL);
for(int i=0;i<num_threads;i++)
free(pThread[i]);
}