I am trying to synchronize the reading of 5 files so each character is read in from a file and then from the next file another character and so on. At the end an array will print out the content. I am able to read from the files but the synchronization is way off. I tried to fix it with a control variable to only run the block of code when it is that files turn but I get a wonky output. Here is my section where I do work on the critical sections
while(!feof(drive1)) {
if(control == 0) {
pthread_mutex_lock(&thread1);
//printf("Mutex lock\n");
c = getc(drive1);
printf("%c", (char)c);
control = 1;
pthread_mutex_unlock(&thread1);
//printf("Mutex unlock\n");
} else if(control == 1) {
pthread_mutex_lock(&thread2);
//printf("Mutex lock\n");
a = getc(drive2);
printf("%c", (char)a);
control = 2;
pthread_mutex_unlock(&thread2);
//printf("Mutex unlock\n");
} else if(control == 2) {
pthread_mutex_lock(&thread3);
//printf("Mutex lock\n");
b = getc(drive3);
printf("%c", (char)b);
control = 3;
pthread_mutex_unlock(&thread3);
//printf("Mutex unlock\n");
} else if(control == 3) {
pthread_mutex_lock(&thread4);
//printf("Mutex lock\n");
d = getc(drive4);
printf("%c", (char)d);
control = 4;
pthread_mutex_unlock(&thread4);
//printf("Mutex unlock\n");
} else if(control == 4) {
pthread_mutex_lock(&thread5);
//printf("Mutex lock\n");
e = getc(drive5);
printf("%c", (char)e);
control = 0;
pthread_mutex_unlock(&thread5);
//printf("Mutex unlock\n");
}
I initially tried it wwith only one thread1 being used to lock the mutexes and unlock them but then decided to create 5 to see if that would help, but it didn't. I also have to use 5 threads to do this for each of the files.
pthread_t th1;
pthread_create(&th1, NULL, processing, NULL);
pthread_t th2;
pthread_create(&th2, NULL, processing, NULL);
pthread_t th3;
pthread_create(&th3, NULL, processing, NULL);
pthread_t th4;
pthread_create(&th4, NULL, processing, NULL);
pthread_t th5;
pthread_create(&th5, NULL, processing, NULL);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
pthread_join(th3, NULL);
pthread_join(th4, NULL);
pthread_join(th4, NULL);
And the output is supposed to be "1234567890abcdefghij"
UPDATE: Based on one of the comments I have modified the code to use the variable "test" as what is being tested in the critical section. With this code I get the output 1212.
void* disk1(void* args) {
//Initializing array of files
FILE *drive[5];
drive[0] = fopen("drive1.data", "r");
drive[1] = fopen("drive2.data", "r");
drive[2] = fopen("drive3.data", "r");
drive[3] = fopen("drive4.data", "r");
drive[4] = fopen("drive5.data", "r");
int c;
if(test < initialFileSize * 2) {
pthread_mutex_lock(&thread1);
if(test % 2 == 0) {
c = getc(drive[0]);
printf("%c", (char)c);
test++;
}
if(test % 2 == 1) {
c = getc(drive[1]);
printf("%c", (char)c);
test++;
}
pthread_mutex_unlock(&thread1);
}
}