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
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
#include "stdafx.h"
#include <pthread.h>
#include <iostream>
#include <locale.h>
using namespace std;
pthread_mutex_t total_mutex = PTHREAD_MUTEX_INITIALIZER;
int p = 2;
int n;
int m;
pthread_t *threads;
int *b, *c;
int **a;
void * process_function(void *pa)
{
int local_m = m / p;
int i = (int)pa;
int j = 0;
int start = i*local_m;
int end = start + local_m - 1;
int it = 0;
int *tmp=(int*)malloc(n*sizeof(int));
for (int i = 0; i < n; i++)
tmp[i] = 0;
for (int k = start; k <= end; k++)
{
for (int j = 0; j < n; j++)
tmp[j] += a[j][k] * b[k];
}
pthread_mutex_lock(&total_mutex);
for (int j = 0; j < n; j++) c[j] += tmp[j];
pthread_mutex_unlock(&total_mutex);
free(tmp);
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 _tmain(int argc, _TCHAR* argv[])
{
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;
}