#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <math.h>
#include <cstring>
using namespace std;
pthread_mutex_t mutex;
int **matrix;
int *vect;
int *result;
struct Param
{
int _beginN;
int _endN;
int _beginM;
int _endM;
};
void block(int _beginN, int _endN, int _beginM, int _endM) // по столбцам
{
int* tmp= new int[_endN-_beginN];
memset(tmp,0,(_endN-_beginN)*sizeof(int));
for (int i = _beginN; i < _endN; i++)
{
for(int j = _beginM; j < _endM; j++)
{
tmp[i-_beginN] += matrix[i][j] * vect[j];
/*pthread_mutex_lock(&mutex);
result[j] += matrix[j][i] * vect[i];
pthread_mutex_unlock(&mutex);*/
}
}
for(int j = _beginN; j < _endN; j++)
{
pthread_mutex_lock(&mutex);
result[j] += tmp[j-_beginN];
pthread_mutex_unlock(&mutex);
}
delete [] tmp;
}
void * blockFunc(void *lpParam)
{
struct Param pr = *((struct Param *)lpParam);
block(pr._beginN, pr._endN, pr._beginM, pr._endM);
delete (struct Param *)lpParam;
}
int main()
{
setlocale(LC_ALL, "Russian");
pthread_mutex_init(&mutex, NULL);
int n = 6, m = 6; //n строки / m столбцы
int partN=3,partM=3;//разбиение
int p = partN*partM; //количество потоков
matrix = new int*[n];
pthread_t **th = new pthread_t*[partN];
for(int i=0; i<partN; i++) th[i]=new pthread_t[partM];
for (int i = 0; i < n; i++)
matrix[i] = new int[m];
cout << "Матрица: " << endl;
srand(time(NULL));
result = new int[n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = rand()%10;
cout << matrix[i][j] << " ";
}
cout << endl;
result[i] = 0;
}
cout << endl;
cout << "Вектор: " << endl;
vect = new int[m];
srand(time(NULL));
for (int j = 0; j < m; j++)
{
vect[j] = rand()%10;
cout << vect[j] << " ";
}
cout << endl;
long t = clock();
cout << endl << "Разбиение по блокам:" << endl;
int _totalN = n/partN;
int _remN = n%partN;
int _endN=0;
int _totalM = m/partM;
int _remM = m%partM;
int _endM=0;
for(int i=0; i<partN; i++)
{
Param *pr=new Param;
pr->_beginN = _endN;
pr->_endN = _remN-- > 0 ? pr->_beginN+_totalN+1 : pr->_beginN+_totalN;
_endN=pr->_endN;
_endM=0;
_remM = m%partM;
for(int j=0; j<partM ;j++)
{
Param *pr2=new Param;
*pr2=*pr;
pr2->_beginM = _endM;
pr2->_endM = _remM-- > 0 ? pr2->_beginM+_totalM+1 : pr2->_beginM+_totalM;
_endM=pr2->_endM;
pthread_create(&th[i][j], NULL, blockFunc, pr2);
}
delete pr;
}
for(int i=0; i<partN; i++)
{
for(int j=0; j<partM; j++)
{
pthread_join(th[i][j], NULL);
}
}
cout << "Результат: ";
t = clock() - t;
for (int i = 0; i < n; i++)
{
cout << result[i] << " ";
}
cout << endl << "Время выполнения: " << t << " ms" << endl;
for (int i = 0; i < n; i++)
delete[] matrix[i];
delete []matrix;
delete []result;
delete []vect;
delete []th;
return 0;
}