57 lines
1.2 KiB
C++
57 lines
1.2 KiB
C++
|
#include "mat_mul.h"
|
||
|
|
||
|
#include <cstdlib>
|
||
|
#include <cstdio>
|
||
|
#include <pthread.h>
|
||
|
|
||
|
#define bs 32
|
||
|
#define min(a, b) (((a) < (b)) ? (a) : (b))
|
||
|
#define max(a, b) (((a) > (b)) ? (a) : (b))
|
||
|
|
||
|
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 chunk = M / num_threads;
|
||
|
int start = pid * chunk;
|
||
|
int end = pid == num_threads - 1 ? M : (pid + 1) * chunk;
|
||
|
|
||
|
float tmp;
|
||
|
|
||
|
for (int kk = 0; kk < K; kk += bs) {
|
||
|
for (int i = start; i < end; ++i) {
|
||
|
for (int k = kk; k < min(kk + bs, K); ++k) {
|
||
|
tmp = A[i * K + k];
|
||
|
for (int j = 0; j < N; ++j) {
|
||
|
C[i * N + j] += tmp * 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 thread[num_threads];
|
||
|
int pid[num_threads];
|
||
|
|
||
|
for (int i = 0; i < num_threads; i++) {
|
||
|
pid[i] = i;
|
||
|
pthread_create(&thread[i], NULL, mat_mul_thread, (void*) &pid[i]);
|
||
|
}
|
||
|
|
||
|
for (int i = 0; i < num_threads; i++) {
|
||
|
pthread_join(thread[i], NULL);
|
||
|
}
|
||
|
|
||
|
}
|