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.
- Producer Consumer Problem using Semaphores | Set 1
- Operating System | Dekker's algorithm
- Operating System | Dining Philosopher Problem Using Semaphores
- Operating System | Peterson's Algorithm (Using processes and shared memory)
- Inter Process Communication
- Peterson's Algorithm for Mutual Exclusion | Set 2 (CPU Cycles and Memory Fence)
- Operating System | Segmentation
- Operating System | Banker's Algorithm
- Readers-Writers Problem | Set 1 (Introduction and Readers Preference Solution)
- Priority Inversion : What the heck !
- Process Synchronization | Monitors
- Operating System | Process Management | Deadlock Introduction
- Operating System | Process Synchronization | Introduction
- Mutex vs Semaphore
- Operating System | Critical Section