Peterson Deadlockavoidance
Peterson Deadlockavoidance
Code:
int main()
{
shmid1 = shmget(k1, sizeof(bool) * 2, IPC_CREAT | 0660); // flag
shmid2 = shmget(k2, sizeof(int) * 1, IPC_CREAT | 0660); // turn
shmid3 = shmget(k3, sizeof(int) * BSIZE, IPC_CREAT | 0660); // buffer
shmid4 = shmget(k4, sizeof(int) * 1, IPC_CREAT | 0660); // time stamp
if (shmid1 < 0 || shmid2 < 0 || shmid3 < 0 || shmid4 < 0) {
perror("Main shmget error: ");
exit(1);
}
SHM3 = (int*)shmat(shmid3, NULL, 0);
int ix = 0;
while (ix < BSIZE) // Initializing buffer
SHM3[ix++] = 0;
struct timeval t;
time_t t1, t2;
gettimeofday(&t, NULL);
t1 = t.tv_sec;
int i = 0; // Consumer
int j = 1; // Producer
while (*state == 1) {
flag[j] = true;
printf("Producer is ready now.\n\n");
*turn = i;
while (flag[i] == true && *turn == i)
;
flag[j] = false;
if (*state == 0)
break;
wait_time = myrand(PWT);
printf("Producer will wait for %d seconds\n\n", wait_time);
sleep(wait_time);
}
exit(0);
}
else
printf("Buffer is empty, nothing can be consumed!!!\n");
printf("Buffer: ");
index = 0;
while (index < BSIZE)
printf("%d ", buf[index++]);
printf("\n");
// Critical Section End
flag[i] = false;
if (*state == 0)
break;
wait_time = myrand(CWT);
printf("Consumer will sleep for %d seconds\n\n", wait_time);
sleep(wait_time);
}
exit(0);
}
// Parent process will now for RT seconds before causing child to terminate
while (1) {
gettimeofday(&t, NULL);
t2 = t.tv_sec;
if (t2 - t1 > RT) // Program will exit after RT seconds
{
*state = 0;
break;
}
}
return 0;
}
Output:
Result/Conclusion:
We have implemented the C program for Peterson's Algorithm to solve the producer-consumer
problem using shared memory and processes on Ubuntu operating system. In this problem
processes share a common, fixed-size buffer in synchronization.
1. Shared memory segments are created for boolean flags, turn variable, buffer, and a time
stamp. The producer and consumer processes are created using fork().
2. The producer and consumer processes use Peterson's Algorithm for mutual exclusion to
access the shared buffer.
3. The producer generates random jobs and adds them to the buffer while the consumer
consumes jobs from the buffer.
4. The program runs for a specified duration (RT) and then signals the processes to terminate.
The parent process waits for both child processes to exit before printing a concluding
message.