include pthread include stdio int sum0 sum1 sum2 pthread_t thread pthr

 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
#include <pthread.h>
#include <stdio.h>
int sum0 = 0, sum1 = 0, sum2 = 0;
pthread_t thread[2];
pthread_barrier_t barr;
void *func(void* p)
{
int arr[5];
int num = (int)(p);
if (num == 0) {
for (int i = 0; i < 5; i++)
arr[i] = i + 1; //{1, 2, 3, 4, 5};
}
if (num == 1) {
for (int i = 0; i < 5; i++)
arr[i] = i + 3; //{3, 4, 5, 6, 7};
}
if (num == 2) {
for (int i = 0; i < 5; i++)
arr[i] = i + 5; //{5, 6, 7, 8, 9};
}
for (int i = 0; i < 5; i++)
{
if (num == 0) {
sum0 += arr[i];
}
if (num == 1) {
sum1 += arr[i];
}
if (num == 2) {
sum2 += arr[i];
}
}
pthread_barrier_wait(&barr);
while (sum0 != sum1 && sum1 != sum2) {
printf("Имеем №1 %d №2 %d №3 %d\n", sum0, sum1, sum2);
pthread_barrier_wait(&barr);
if (num == 0) {
if (sum0 > sum1) {
sum0--;
arr[0]--;
}
if (sum0 < sum1) {
sum0++;
arr[0]++;
}
}
if (num == 2) {
if (sum2 > sum1) {
sum2--;
arr[2]--;
}
if (sum2 < sum1) {
sum2++;
arr[2]++;
}
}
pthread_barrier_wait(&barr);
printf("Поменяли\n");
pthread_barrier_wait(&barr);
}
pthread_barrier_wait(&barr);
printf("Результат №1 %d №2 %d №3 %d\n", sum0, sum1, sum2);
return NULL;
}
int main()
{
pthread_barrier_init(&barr, NULL, 3);
pthread_create(&thread[0], NULL, func, (void *)0);
pthread_create(&thread[1], NULL, func, (void *)1);
//func((void*)1);
func((void*)2);
return 0;
}