73 lines
1.4 KiB
C++
73 lines
1.4 KiB
C++
#include "mat_mul.h"
|
|
|
|
#include <cstdlib>
|
|
#include <cstdio>
|
|
#include <pthread.h>
|
|
#include <algorithm>
|
|
|
|
#define BLOCK_SIZE 32
|
|
|
|
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
|
|
int i,j,k;
|
|
int kk;
|
|
int Bsize = BLOCK_SIZE;
|
|
int id = *(int*)data;
|
|
int slice = M / num_threads;
|
|
int start_ptr = slice * id;
|
|
int end_ptr = (id == (num_threads-1)) ? M : (id+1) * slice;
|
|
|
|
float A_mac;
|
|
|
|
for (kk = 0; kk < K; kk += Bsize)
|
|
{
|
|
for (i = start_ptr; i < end_ptr; ++i)
|
|
{
|
|
for (k = kk; k < std::min(kk + Bsize, K); ++k)
|
|
{
|
|
A_mac = A[i*K+k];
|
|
|
|
for (j = 0; j < N; ++j)
|
|
{
|
|
C[i*N+j] += A_mac * 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;
|
|
|
|
pthread_t *pthreads;
|
|
pthreads = (pthread_t*) malloc(sizeof(pthread_t) * num_threads);
|
|
|
|
for (i=0; i<num_threads; i++)
|
|
{
|
|
int * thread_id = (int *) malloc(sizeof(int));
|
|
// tID = i;
|
|
// thread_id = &tID;
|
|
*thread_id = i; //init
|
|
|
|
pthread_create(&pthreads[i], NULL, mat_mul_thread, thread_id);
|
|
}
|
|
|
|
for (i = 0; i < num_threads; i++)
|
|
{
|
|
pthread_join(pthreads[i], NULL);
|
|
}
|
|
free(pthreads);
|
|
}
|
|
|