#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;
}