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 firstname.lastname@example.org. 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.
- Peterson's Algorithm for Mutual Exclusion | Set 2 (CPU Cycles and Memory Fence)
- Program for Banker's Algorithm | Set 1 (Safety Algorithm)
- LFU (Least Frequently Used) Cache Implementation
- TCP Server-Client implementation in C
- Operating System | Banker's Algorithm
- Operating System | Dekker's algorithm
- Operating System | Bakery Algorithm
- Program for Optimal Page Replacement Algorithm
- Program for SSTF disk scheduling algorithm
- Operating System | Deadlock detection algorithm
- Operating System | Program for Next Fit algorithm in Memory Management
- CPU Scheduling | Longest Remaining Time First (LRTF) algorithm
- Operating System | Peterson's Algorithm (Using processes and shared memory)
- Operating System | Banker's Algorithm : Print all the safe state (or safe sequences)