88 lines
2.0 KiB
C++
88 lines
2.0 KiB
C++
|
#include "mat_mul.h"
|
||
|
#include <cstdlib>
|
||
|
#include <cstdio>
|
||
|
#include <pthread.h>
|
||
|
#include <algorithm>
|
||
|
#define bsize 64
|
||
|
|
||
|
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 = 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 pid = *(int*)data;
|
||
|
int block = M / num_threads;
|
||
|
int start = pid*block;
|
||
|
int end = (pid == num_threads-1)? M: (pid+1)*block;
|
||
|
float Mat_A;
|
||
|
|
||
|
for (int kk=0; kk<K; kk+=bsize){
|
||
|
for(int i=start; i<end; ++i){
|
||
|
for(int k =kk; k<std::min(kk+bsize, K); ++k){
|
||
|
Mat_A = A[i*K + k];
|
||
|
for(int j= 0; j<N; ++j){
|
||
|
C[i*N+j] += Mat_A * 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 thread;
|
||
|
//pthread_create(&thread, NULL, mat_mul_thread, NULL);
|
||
|
//pthread_join(thread, NULL);
|
||
|
|
||
|
/*
|
||
|
pthread_t p_thread[num_threads];
|
||
|
int thread_id[num_threads];
|
||
|
int result[num_threads];
|
||
|
//int status;
|
||
|
|
||
|
for (int i=0; i<num_threads; i++){
|
||
|
thread_id[i] = pthread_create(&p_thread[i], NULL, mat_mul_thread, NULL);
|
||
|
|
||
|
if(thread_id[i]<0){
|
||
|
perror("thread create error : ");
|
||
|
exit(0);
|
||
|
}
|
||
|
else{
|
||
|
printf("thread %d : created\n", i);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for(int j=0; j<num_threads; j++){
|
||
|
pthread_join(p_thread[j], (void **)&result[j]);
|
||
|
printf("thread join : %d\n", j);
|
||
|
}
|
||
|
*/
|
||
|
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);
|
||
|
}
|
||
|
|
||
|
}
|