include iostream include pthread include Windows using namespace std i

  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
#include <iostream>
#include <pthread.h>
#include <Windows.h>
using namespace std;
int p;
pthread_t *thread;
struct ARGS
{
int num_thread, n;
double *number;
};
void *function_thread(void *pa)
{
Sleep(1000);
ARGS *arg = (ARGS *)pa;
double *status_addr;
int index = 1, count = p, num_thread = arg->num_thread;
for (int i = 1; i < arg->n; i++) arg->number[0] += arg->number[i];
while (count > 1)
{
if (num_thread % 2 == 0 && num_thread != count - 1)
{
if (pthread_join(thread[arg->num_thread + index], (void **)&status_addr))
{
cout << "function_thread: Ошибка при выполнении функции pthread_join\n";
exit(0);
}
arg->number[0] += *status_addr;
num_thread /= 2;
index *= 2;
count % 2 == 0 ? count /= 2 : count = count / 2 + 1;
}
else break;
}
return arg->number;
}
int main()
{
setlocale(LC_ALL, "Russian");
int n, i, index = 0, dev, mod, denom = 1;
double *number, *result;
ARGS *args;
cout << "Укажите число элементов последовательности: ";
cin >> n;
cout << "Укажите число задач: ";
cin >> p;
dev = n / p;
mod = n % p;
number = (double *)malloc(n * sizeof(double));
thread = (pthread_t *)malloc(p * sizeof(pthread_t));
args = (ARGS *)malloc(p * sizeof(ARGS));
/* Pяд Лейбница */
for (i = 0; i < n; i++)
{
if (i % 2 == 0) number[i] = 1.0 / denom;
else number[i] = -1.0 / denom;
denom += 2;
}
for (i = 0; i < p; i++)
{
args[i].num_thread = i;
args[i].n = dev;
if (mod > 0)
{
args[i].n++;
mod--;
}
args[i].number = (double *)malloc(args[i].n * sizeof(double));
for (int j = 0; j < args[i].n; j++) args[i].number[j] = number[index++];
if (pthread_create(thread + i, 0, function_thread, args + i))
{
cout << "Ошибка при выполнении функции pthread_create\n";
return 1;
}
}
if (pthread_join(thread[0], (void **)&result))
{
cout << "Ошибка при выполнении функции pthread_join\n";
return 2;
}
cout << "Результат: " << *result * 4 << endl;
free(number);
free(thread);
for (i = 0; i < p; i++) free(args[i].number);
free(args);
return 0;
}