For an assignment I am writing a program for the producer consumer problem.
As per the assignment specs I have written 3 programs with a shared memory
The shared memory contains the buffer and the semaphores in a struct.
The parent initialises the semaphores, shared memory and pointers, runs the programs and catches the return codes
The reader reads from a file, decrypts the data, places it into the buffer
The writer reads from the buffer, and prints output to the screen
Currently I have 2 readers and 1 writer.
Everything compiles fine but I keep getting a deadlock and I am hoping someone can point out the fault in my logic
Here is the relevant code.
reader
writerCode:while (fgets(read_buffer, BUFFER_SLOT_SIZE, fp) != '\0') { /* Decrypt data. Item produced */ for (i = 0; i < BUFFER_SLOT_SIZE; i++) { read_buffer[i] = decrypt(read_buffer[i]); if (read_buffer[i] == '\n') { break; } } sem_wait(&smp->empty); /* Decrement empty count */ sem_wait(&smp->mutex); /* Enter critical region */ strcpy(smp->buffer[smp->head], read_buffer); /* Add item to buffer */ smp->head = (smp->head + 1) % BUFFER_SIZE; /* Increment head pointer */ sem_post(&smp->mutex); /* Exit critical reagion */ sem_post(&smp->full); /* Increment full count */ nanosleep(&tv, NULL); /* Sleep for random time */ } /* Increment completed counter. Use mutex to ensure exclusion */ sem_wait(&smp->mutex); smp->completed++; sem_post(&smp->mutex);
cheersCode:/* Continue while data in the buffer */ while (smp->completed < 2 && value != 0) { sem_wait(&smp->full); /* Decrement full count */ sem_wait(&smp->mutex); /* Enter critical region */ strcpy(write_buffer, smp->buffer[smp->tail); /* Read item from the buffer */ smp->tail = (smp->tail + 1) % BUFFER_SIZE; /* Increment tail pointer */ sem_post(&smp->mutex); /* Exit critical region */ sem_post(&smp->empty); /* Increment empty count */ printf("%s", write_buffer); /* Perform action on item */ nanosleep(&tv, NULL); /* Sleep for random time */ sem_getvalue(&smp->empty, &value); /* Get value of empty */ }
Strider1974



LinkBack URL
About LinkBacks



