include stdafx include pthread include iostream include locale using n

 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
#include "stdafx.h"
#include <pthread.h>
#include <iostream>
#include <locale.h>
using namespace std;
int p = 2;
int n;
int m;
pthread_t *threads;
int *b, *c;
int **a;
void * process_function(void *pa)
{
int local_n = n / p;
int i = (int)pa;
int start = i*local_n;
int end = start + local_n - 1;
for (int k = start; k <= end; k++)
for (int j = 0; j<m; j++)
c[k] += a[k][j] * b[j];
return 0;
}
int create_threads()
{
if (!(threads = (pthread_t*)malloc(p*sizeof(pthread_t))))
{
fprintf(stderr, "Not enought memory!\n");
return 1;
}
for (int i = 0; i < p; i++)
if (pthread_create(threads + i, 0, process_function, (void*)i))
{
fprintf(stderr, "thread #%d!\n", i);
return 2;
}
return 0;
}
int main()
{
setlocale(LC_ALL, "Rus");
cout << "Введите количество строк: ";
cin >> n;
cout << "\nВведите количество столбцов: ";
cin >> m;
cout << '\n';
a = (int**)malloc(n*sizeof(int));
for (int i = 0; i < n;i++)
a[i] = (int*)malloc(m*sizeof(int));
b = (int*)malloc(m*sizeof(int));
c = (int*)malloc(n*sizeof(int));
for (int i = 0; i < n; i++)
c[i] = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
a[i][j] =rand() % 5;
cout << a[i][j] << ' ';
if (j == m - 1) cout << "\n";
}
cout << endl;
for (int i = 0; i < m; i++)
{
b[i] =rand() % 5;
cout << b[i] << "\n";
}
cout << endl;
int err = create_threads();
if (err != 0)
return err;
for (int i = 0; i < p;i++)
if (pthread_join(threads[i],0))
fprintf(stderr, "wait thread #d!\n", i);
cout << "Результат: \n";
for (int i = 0; i<n; i++) cout << c[i] << '\n';
for (int i = 0; i < n; i++)
free(a[i]);
free(a);
free(b);
free(c);
return 0;