#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <math.h>
using namespace std;
pthread_mutex_t mutex;
int **mas;
int *vect;
int *result;
struct BlockData
{
int st_n;
int _end_n;
int st_m;
int _end_m;
};
void *blockMult(int stn, int _endn, int stm, int _endm)
{
for (int i = stn; i < _endn; i++)
{
for(int j = stm; j < _endm; j++)
{
pthread_mutex_lock(&mutex);
result[i] += mas[i][j] * vect[j];
//cout << result[i] << " ";
pthread_mutex_unlock(&mutex);
}
}
}
void *rowFunc(void *lpParam)
{
//struct Data dt = *((struct Data *)lpParam);
struct BlockData dt = *((struct BlockData *)lpParam);
blockMult(dt.st_n, dt._end_n, dt.st_m, dt._end_m);
}
int main()
{
setlocale(LC_ALL, "Russian");
pthread_mutex_init(&mutex, NULL);
const int p = 1;
const int n = 2, m = 4;
mas = new int*[n];
pthread_t *th = new pthread_t[p];
for (int i = 0; i < n; i++)
mas[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++)
{
mas[i][j] = rand()%3;
cout << mas[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()%3;
cout << vect[j] << " ";
}
cout << endl;
BlockData *dt = new BlockData[p];
for (int i = 0; i < p; i++)
{
for (int j = 0; j < p; j++)
{
dt[j].st_n = i * round(n/p);
dt[j]._end_n = (i == (p - 1)) ? (i * round(n/p) + round(n/p) + n % p) : (i * round(n/p) + round(n/p));
dt[j].st_m = j * round(m/p);
dt[j]._end_m = (j == (p - 1)) ? (j * round(m/p) + round(m/p) + m % p) : (j * round(m/p) + round(m/p));
cout << "dt[i].st_n = " << dt[j].st_n << " dt[i]._end_n = "
<< dt[j]._end_n << " dt[i].st_m = " << dt[j].st_m << " dt[i]._end_m = " << dt[j]._end_m << endl;
pthread_create(&th[j], NULL, rowFunc, &dt[j]);
}
}
cout << "Результат: ";
for (int i = 0; i < p; i++)
{
pthread_join(th[i], NULL);
}
for (int i = 0; i < n; i++)
{
cout << result[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
delete[] mas[i];
delete []mas;
delete []dt;
delete []result;
delete []vect;
delete []th;
return 0;
}