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
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
using namespace std;
struct Data
{
int *mas;
int *vec;
int length;
};
int rowMult(int *mas, int *vec, int length)
{
int result = 0;
for(int i = 0; i < length; i++)
result += mas[i] * vec[i];
return result;
}
void *rowFunc(void *lpParam)
{
struct Data dt = *((struct Data *)lpParam);
int* result = (int*) malloc(sizeof(int));
*result = rowMult(dt.mas, dt.vec, dt.length);
return result;
}
int main()
{
setlocale(LC_ALL, "Russian");
const int n = 3, m = 4;
int **mas = new int*[n];
pthread_t *th = new pthread_t[n];
for (int i = 0; i < n; i++)
mas[i] = new int[m];
cout << "Матрица: " << endl;
srand(time(NULL));
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;
}
cout << endl;
Data dt;
cout << "Вектор: " << endl;
int *vect = new int[m];
int *tempMas = new int[m];
srand(time(NULL));
for (int j = 0; j < m; j++)
{
vect[j] = rand()%10;
tempMas[j] = 0;
cout << vect[j] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
tempMas[j] = mas[i][j];
}
dt.length = m;
dt.mas = tempMas;
dt.vec = vect;
pthread_create(&th[i], NULL, rowFunc, &dt);
usleep(10000);
}
void *t;
int *resultMas = new int[n];
cout << endl;
for (int i = 0; i < n; i++)
{
pthread_join(th[i], (void**)&t);
resultMas[i] = *(int*)t;
cout << resultMas[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
delete[] mas[i];
delete []mas;
delete []vect;
delete []th;
return 0;
}