chundoong-lab-ta/SamsungDS22/submissions/HW2/c.m.lee/mat_mul.cpp

60 lines
1.3 KiB
C++

#include "mat_mul.h"
#include <cstdlib>
#include <cstdio>
#include <pthread.h>
#ifndef BLK_SIZE
#define BLK_SIZE 48
#endif
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
static void* mat_mul_thread(void *data) {
long id = *((long *)data);
long chunk = M / num_threads;
long start = chunk * id;
long end = start + chunk;
if (id == num_threads - 1)
end = M;
for (int kk = 0; kk < K; kk += BLK_SIZE) {
for (int i = start; i < end; i++) {
for (int k = kk; k < MIN(kk + BLK_SIZE, K); k++) {
register float 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 = (pthread_t *)malloc(_num_threads * sizeof(pthread_t));
long *ids = (long *)malloc(_num_threads * sizeof(long));
for (int i = 0; i < _num_threads; i++) {
ids[i] = i;
pthread_create(&threads[i], NULL, mat_mul_thread, (void *)&ids[i]);
}
for (int i = 0; i < _num_threads; i++) {
pthread_join(threads[i], NULL);
}
free(ids);
free(threads);
}