chundoong-lab-ta/SamsungDS22/submissions/HW2/jihye65.park/mat_mul.cpp

46 lines
1.0 KiB
C++
Raw Normal View History

2022-09-29 18:01:45 +09:00
#include "mat_mul.h"
#include <cstdlib>
#include <cstdio>
#include <pthread.h>
#include <algorithm>
static float *A, *B, *C;
static int M, N, K;
static int num_threads;
static void* mat_mul_thread(void *data){
int pid = *(int*) data;
int blk = 45;
for(int kk=0; kk<K; kk+=blk)
for(int i=pid*M/num_threads; i<(pid+1)*M/num_threads; ++i)
for(int k=kk; k<std::min(kk+blk, K); ++k){
for(int j=0; j<N; ++j){
C[i*N+j] += A[i*K+k] * 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* threads;
threads = (pthread_t*) malloc(sizeof(pthread_t) * num_threads);
for(int i=0; i< num_threads; i++){
int* pid = (int*) malloc(sizeof(int));
*pid = i;
pthread_create(&threads[i], NULL, mat_mul_thread, pid);
}
for(int i=0; i<num_threads; i++){
pthread_join(threads[i], NULL);
}
}