Peterson’s Algorithm is a classical software-based solution for the Critical Section Problem. It ensures mutual exclusion, progress, and bounded waiting using only shared variables — without needing special hardware instructions.
int flag[2] = {FALSE, FALSE}; // Flags to indicate if a process wants to enter CS int turn = 0; // Whose turn it is to enter CS
void* process0(void* arg) { for (int i = 0; i < 5; i++) { flag[0] = TRUE; turn = 1; while (flag[1] && turn == 1); // Wait if process1 wants to enter CS
// Critical Section printf("Process 0 is in the critical section\n"); sleep(1); // Simulate work in CS
// Exit Section flag[0] = FALSE; printf("Process 0 is leaving the critical section\n");
void* process1(void* arg) { for (int i = 0; i < 5; i++) { flag[1] = TRUE; turn = 0; while (flag[0] && turn == 0); // Wait if process0 wants to enter CS
// Critical Section printf("Process 1 is in the critical section\n"); sleep(1); // Simulate work in CS
// Exit Section flag[1] = FALSE; printf("Process 1 is leaving the critical section\n");