chundoong-lab-ta/SamsungDS22/submissions/HW2/ssjoong.kim/mat_mul.cpp

89 lines
1.6 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;
static void* mat_mul_thread(void *data) {
// TODO: parallelize & optimize matrix multiplication
//for (int i = row_start; i < row_end; ++i) {
//for (int i = 0; i < M; ++i) {
// for (int j = 0; j < N; ++j) {
// for (int k = 0; k < K; ++k) {
// C[i * N + j] += A[i * K + k] * B[k * N + j];
// }
// }
//}
int x = * (int *) data;
int start = x * (M / num_threads);
int end = start + (M / num_threads);
if (x == num_threads - 1)
{
end = M;
}
float Aik;
int bs = 50;
int k_max;
for (int kk = 0; kk < K; kk += bs)
{
if ((kk + bs) < K)
{
k_max = kk + bs;
}
else
{
k_max = K;
}
for (int i = start; i < end; ++i)
{
for (int k = kk; k < k_max; ++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;
// TODO: create '_num_threads' pthreads
int i;
int* p = (int*)malloc(sizeof(int) * num_threads);
pthread_t thread[num_threads];
for (i = 0; i < num_threads; i++)
{
p[i] = i;
pthread_create(&thread[i], NULL, mat_mul_thread, &p[i]);
}
for (i = 0; i <num_threads; i++)
{
pthread_join(thread[i], NULL);
}
free(p);
}