Sitemap

Peterson’s Algorithm in C

2 min readApr 2, 2025

--

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.

Press enter or click to view image in full size
Photo by Michael Dziedzic on Unsplash

Key Concepts

1. Mutual Exclusion

  • Only one process can be in the Critical Section (CS) at a time.
  • A process checks if the other one wants to enter the CS before proceeding.

Get ved prakash singh’s stories in your inbox

Join Medium for free to get updates from this writer.

2. Progress

  • If no process is in the CS, the one that wants to enter should not be indefinitely blocked.

3. Bounded Waiting

  • A process should not wait indefinitely to enter the CS; it will get its turn fairly.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define TRUE 1
#define FALSE 0

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");

sleep(1); // Simulate non-critical section
}
return NULL;
}

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");

sleep(1); // Simulate non-critical section
}
return NULL;
}

int main() {
pthread_t t0, t1;

// Create two threads simulating two processes
pthread_create(&t0, NULL, process0, NULL);
pthread_create(&t1, NULL, process1, NULL);

// Wait for both threads to finish
pthread_join(t0, NULL);
pthread_join(t1, NULL);

return 0;
}

--

--