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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.