0% found this document useful (0 votes)
69 views2 pages

Peterson Algorithms

Uploaded by

karthy46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views2 pages

Peterson Algorithms

Uploaded by

karthy46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Peterson's Algorithm in Process Synchronization

Last Updated : 29 Aug, 2025

Peterson’s Algorithm is a classic software-based solution for the critical section problem in operating
systems. It ensures mutual exclusion between two processes, meaning only one process can access a
shared resource at a time, thus preventing race conditions.

The algorithm uses two shared variables:

 flag[i]: shows whether process i wants to enter the critical section.

 turn: indicates whose turn it is to enter if both processes want to access the critical section
at the same time.

The Algorithm

For process Pi:

do {
flag[i] = true; // Pi wants to enter
turn = j; // Give turn to Pj

while (flag[j] && turn == j); // Wait if Pj also wants to enter

// Critical Section

flag[i] = false; // Pi leaves critical section

// Remainder Section
} while (true);

For process Pj:

do {
flag[j] = true;
turn = i;

while (flag[i] && turn == i);

// Critical Section

flag[j] = false;

// Remainder Section
} while (true);

Step-by-Step Explanation

1. Intent to Enter: A process sets its flag to true when it wants to enter the critical section.
2. Turn Assignment: It sets the turn variable to the other process, giving the other process the
chance to enter first if it also wants to.

3. Waiting Condition: A process waits if the other process also wants to enter and it is the
other’s turn.

4. Critical Section: Once the condition is false, the process enters the critical section safely.

5. Exit: On leaving, the process resets its flag to false, allowing the other process to proceed.

This guarantees:

 Mutual Exclusion: Only one process enters CS.

 Progress: A process will eventually enter CS if no other is inside.

 Bounded Waiting; No process waits indefinitely.

Example Use Cases

Peterson’s Algorithm can be used (theoretically) in:

 Accessing a shared printer: Peterson's solution ensures that only one process can access the
printer at a time when two processes are trying to print documents.

 Reading and writing to a shared file: It can be used when two processes need to read from
and write to the same file, preventing concurrent access issues.

 Competing for a shared resource: When two processes are competing for a limited resource,
such as a network connection or critical hardware, Peterson’s solution ensures mutual
exclusion to avoid conflicts.

You might also like