Программа запускает 3 нити и выводит в потом ввода счастливое число из соответствубщего файла. Используется мьютекс

  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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/times.h>
typedef struct Parameters {
int number;
FILE *input;
}Parameters;
// Thread body function
void* run(void* arg);
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main() {
Parameters *masParameters;
masParameters = (Parameters*)malloc(3*sizeof(Parameters));
for (int i = 0; i < 3; i++)
masParameters[i].number = i;
if ((masParameters[0].input = fopen("input1.txt", "r")) == NULL) {
printf("Error to open input1.txt");
return -1;
}
if ((masParameters[1].input = fopen("input2.txt", "r")) == NULL) {
printf("Error to open input2.txt");
return -1;
}
if ((masParameters[2].input = fopen("input3.txt", "r")) == NULL) {
printf("Error to open input3.txt");
return -1;
}
pthread_t *thread;
thread = (pthread_t*)malloc(3*sizeof(pthread_t));
srand(time(NULL)); // Set the random generator
for (int i = 0; i < 3; i++) {
int res = pthread_create(&thread[i], NULL, &run, &masParameters[i]);
if (res != 0) {
printf("Cannot create thread %d", i+1);
exit(1);
}
pthread_mutex_lock(&mutex);
printf("Thread %d is created.\n", i+1);
pthread_mutex_unlock(&mutex);
}
for (int i = 0; i < 3; i++)
pthread_join(thread[i], NULL);
pthread_mutex_destroy(&mutex);
free(thread);
fclose(masParameters[0].input);
fclose(masParameters[1].input);
fclose(masParameters[2].input);
free(masParameters);
return 0;
}
void* run(void* arg) {
Parameters param = *((Parameters *) arg);
int number = param.number;
FILE *input = param.input;
bool fl = false;
while(!fl) {
int r = rand();
r %= 3;
pthread_mutex_lock(&mutex);
char tmp = fgetc(input);
char bb[6];
bb[0] = tmp;
for (int i = 1; i < 6; i++)
bb[i] = fgetc(input);
int buf = 0;
buf += bb[0] - '0';
buf += bb[1] - '0';
buf += bb[2] - '0';
buf -= bb[3] - '0';
buf -= bb[4] - '0';
buf -= bb[5] - '0';
//printf("%d %d %c%c%c%c%c%c\n", number+1, buf, bb[0], bb[1], bb[2], bb[3], bb[4], bb[5]);
if (buf == 0)
printf("%d %c%c%c%c%c%c\n", number+1, bb[0], bb[1], bb[2], bb[3], bb[4], bb[5]);
if (fgetc(input) == EOF) {
fl = true;
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
sched_yield(); // Give time to other threads
sleep(r+1); // Sleep does the same...
}
return NULL;
}