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