include iostream include stdlib include stdio include pthread include

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
#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;
}