VOOZH about

URL: https://www.geeksforgeeks.org/c/petersons-algorithm-for-mutual-exclusion-set-1/

⇱ Peterson's Algorithm for Mutual Exclusion | Set 1 (Basic C implementation) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Peterson's Algorithm for Mutual Exclusion | Set 1 (Basic C implementation)

Last Updated : 13 Jan, 2025

Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support.

Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popular way to do this is by using Peterson's Algorithm for mutual Exclusion. It was developed by Peterson in 1981 though the initial work in this direction was done by Theodorus Jozef Dekker who came up with Dekker's algorithm in 1960, which was later refined by Peterson and came to be known as Peterson's Algorithm.

Basically, Peterson’s algorithm provides guaranteed mutual exclusion by using only the shared memory. It uses two ideas in the algorithm:

  1. Willingness to acquire lock.
  2. Turn to acquire lock.

Prerequisite: Multithreading in C

Explanation: The idea is that first a thread expresses its desire to acquire a lock and sets flag[self] = 1 and then gives the other thread a chance to acquire the lock. If the thread desires to acquire the lock, then, it gets the lock and passes the chance to the 1st thread. If it does not desire to get the lock then the while loop breaks and the 1st thread gets the chance.

The below code implementation uses the POSIX threads (pthread), which is common in C programs and lower-level system programming but requires more manual work and typecasting.

Output: 

Thread Entered: 1
Thread Entered: 0
Actual Count: 2000000000 | Expected Count: 2000000000

The produced output is 2*109 where 109 is incremented by both threads.

Read more about Peterson's Algorithm for Mutual Exclusion | Set 2

Comment