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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#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 Data
{
int st;
int _end;
int m;
};
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[j] += mas[j][i] * vect[i];
pthread_mutex_unlock(&mutex);
}
}
}
void *colMult(int st, int _end, int n)
{
for (int i = st; i < _end; i++)
{
for(int j = 0; j < n; j++)
{
pthread_mutex_lock(&mutex);
result[j] += mas[j][i] * vect[i];
pthread_mutex_unlock(&mutex);
}
}
}
void rowMult(int st, int _end, int m)
{
for (int j = st; j < _end; j++)
{
for(int i = 0; i < m; i++)
{
pthread_mutex_lock(&mutex);
result[j] += mas[j][i] * vect[i];
pthread_mutex_unlock(&mutex);
}
}
}
void *rowFunc(void *lpParam)
{
struct Data dt = *((struct Data *)lpParam);
rowMult(dt.st, dt._end, dt.m);
}
int main()
{
setlocale(LC_ALL, "Russian");
pthread_mutex_init(&mutex, NULL);
const int p = 3;
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()%10;
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()%10;
cout << vect[j] << " ";
}
cout << endl;
Data *dt = new Data[p];
for (int i = 0; i < p; i++)
{
// по Строкам
dt[i].m = m;
dt[i].st = i * round(n/p);
dt[i]._end = (i == (p - 1)) ? (i * round(n/p) + round(n/p) + n % p) : (i * round(n/p) + round(n/p));
// по Столбцам
//dt[i].m = n;
//dt[i].st = i * round(m/p);
//dt[i]._end = (i == (p - 1)) ? (i * round(m/p) + round(m/p) + m % p) : (i * round(m/p) + round(m/p));
pthread_create(&th[i], NULL, rowFunc, &dt[i]);
}
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;
}