Problem: Given 2 process 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 Algorithm for mutual Exclusion. It was developed by Peterson in 1981 though the initial work in this direction by 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,
- Willingness to acquire lock.
- Turn to acquire lock.
Prerequisite : Multithreading in C
The idea is that first a thread expresses its desire to acquire 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 then 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.
Implementation in C language
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.
This article is contributed by Pinkesh Badjatiya . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Lamport's Algorithm for Mutual Exclusion in Distributed System
- Maekawa’s Algorithm for Mutual Exclusion in Distributed System
- Suzuki–Kasami Algorithm for Mutual Exclusion in Distributed System
- Peterson's Algorithm for Mutual Exclusion | Set 2 (CPU Cycles and Memory Fence)
- Ricart–Agrawala Algorithm in Mutual Exclusion in Distributed System
- Mutual exclusion in distributed system
- Implementation of Least Recently Used (LRU) page replacement algorithm using Counters
- Program for Banker's Algorithm | Set 1 (Safety Algorithm)
- Least Frequently Used (LFU) Cache Implementation
- TCP Server-Client implementation in C
- Stack Implementation in Operating System uses by Processor
- Implementation of Non-Preemptive Shortest Job First using Priority Queue
- LRU Approximation (Second Chance Algorithm)
- LOOK Disk Scheduling Algorithm
- C-LOOK Disk Scheduling Algorithm