Process Synchronization Algorithms Guide
Process Synchronization Algorithms Guide
2. SOFTWARE-BASED SOLUTIONS
Ye solutions user mode mein implement hote hain without OS support.
// Jab lock 0 ho gaya, to lock ko 1 set karo (apne CS ko occupy kar raha hoon)
1
lock = 1; // Critical section mein entry le raha hoon, isliye lock = 1
}
// Main Program
main() {
entry_section(); // Entry section ko call karo
critical_section(); // Critical section ko execute karo
exit_section(); // Exit section ko call karo
}
2
void process_P0() {
while(1) { // Infinite loop - process har baar ye kaam karta hai
// ENTRY SECTION
while(turn != 0) { // Agar turn 0 nahi hai (matlab P1 ki turn hai)
// to tab tak wait karo jab tak P0 ki turn aa jaaye
// Busy waiting - CPU cycle waste ho rahi hai lekin shuddha spin lock
}
// CRITICAL SECTION
// Ab P0 ki turn hai, isliye critical section ko safely execute kar sakte hain
shared_data++; // Shared variable ko increment karo
// Yahan sirf P0 execute hoga (P1 entry_section mein stuck hai)
// EXIT SECTION
turn = 1; // Ab P1 ko turn dedo (P0 ki jaankari P1 ko "Hey, ab teri turn hai")
// REMAINDER SECTION
// Kuch aur kaam karo jo shared data ko affect nahi karta
}
}
// ENTRY SECTION
while(turn != 1) { // Agar turn 1 nahi hai (matlab P0 ki turn hai)
// to tab tak wait karo
// Busy waiting
}
// CRITICAL SECTION
shared_data++; // Shared variable ko increment karo
// Ab sirf P1 execute hoga
// EXIT SECTION
turn = 0; // Ab P0 ko turn dedo
// REMAINDER SECTION
}
}
Properties:
• � Mutual Exclusion: Haan, sirf ek ek process CS mein jaata hai
3
• � Progress: Nahi. Agar P0 CS mein nahi jana chahta but P1 jana chahta,
to P1 kabhi entry nahi le sakta
• � Bounded Waiting: Haan, har process ko ek explicit turn mila
// ENTRY SECTION
flag[i] = true; // Apni flag ko true set karo (Haan main interested hoon CS mein)
// Is line se signal karte hain ki "Main entry lena chahta hoon"
4
// Jab ye condition false ho jaaye:
// 1. ya to dusra process interested nahi hai (flag[j] = false)
// 2. ya to turn mera ho gaya (turn = i)
// To entry le sakte ho
// CRITICAL SECTION
// Yahan sirf ek process execute hota hai
shared_data++; // Shared resource ko access karo
// Mutual exclusion guaranteed hai!
// EXIT SECTION
flag[i] = false; // Apni flag ko false karo (Main exit ho gaya, ab interested nahi)
// Signal karte hain "Main CS mein nahi jana"
// REMAINDER SECTION
// Kuch aur kaam jo CS se independent hai
}
}
Time P0 P1 Status
---- --- --- ------
1 flag[0]=true flag[1]=true Dono interested
2 turn=1 (P1 ko priority) turn=0 (P0 ko priority)
3 Check: flag[1]&&turn==0? Check: flag[0]&&turn==1?
True && True = Spin! True && False = EXIT!
P0 busy waiting karo P1 enter karta hai!
4 CS mein execute
5 flag[1]=false (exit)
6 Check: flag[1]&&turn==0?
False && True = EXIT!
P0 enters CS!
7 CS mein execute
8 flag[0]=false (exit)
5
2.4 DEKKER’S ALGORITHM
Type: Software-based, Two-Process Solution (First Correct Solution!)
while(1) {
// ENTRY SECTION
flag[i] = true; // Apna interest declare karo ("Main interested hoon")
// Check karo: agar dusre ki turn hai to apne apna interest withdraw karo
if(turn == j) { // Agar dusra process ki priority hai
flag[i] = false; // Apna interest remove karo ("Thik hai, tu ja")
// CRITICAL SECTION
// Yahan sirf main hoon, dusra CS mein nahi hai
shared_data++;
// EXIT SECTION
turn = j; // Ab dusre process ko turn dedo
flag[i] = false; // Apna interest remove karo
}
}
6
Properties (Sabhi 3 satisfied!):
• � Mutual Exclusion: Guaranteed hai
• � Progress: Ensured hai
• � Bounded Waiting: Fairness maintained hai
Historical Significance: Ye pehla correct solution tha critical section problem
ke liye!
while(1) {
// ENTRY SECTION - Bakery mein token lena (jaise real bakery mein)
choosing[i] = true; // Main apna number choose kar raha hoon (ticket le raha hoon)
// Ab jab tak mere se pehle wale process ko priority na ho, wait karo
for(int j = 0; j < N; j++) { // Sabhi processes ko check karo
if(j != i) { // Apne alag, dusre processes dekho
7
while(choosing[j]) {
// j apna number choose kar raha hai, isiliye wait karo
// Jab choosing[j] false ho to proceed karo
}
// CRITICAL SECTION
// Ab meri turn hai! Sabhi ka priority check kiya, sabse pehle main hoon
shared_data++;
// EXIT SECTION
number[i] = 0; // Apna ticket number clear karo (queue se bahar niklo)
// (0, i) sabse last priority hai, isliye sab pehle jayenge
}
}
Example (Hinglish):
Scenario: 3 processes P0, P1, P2 hain
Time P0 P1 P2
---- --- --- ---
1 choosing[0]=true choosing[1]=true choosing[2]=true
2 number[0]=5 number[1]=5 number[2]=5
3 choosing[0]=false choosing[1]=false choosing[2]=false
4 Check order:
(5,0) vs (5,1) vs (5,2)
(5,0) < (5,1) < (5,2)
P0 entry le!
5 CS execute Wait... Wait...
6 number[0]=0 (exit) Check redo:
(0,0) vs (5,1) vs (5,2)
(5,1) < (5,2)
P1 entry le!
7 CS execute Wait...
8
8 number[1]=0 (exit) Check redo:
(0,1) vs (0,2)
P2 entry le!
9 CS execute
10 number[2]=0 (exit)
Properties:
• � Works for N processes (unlimited processes possible!)
• � Mutual Exclusion: Guaranteed
• � Progress: Ensured
• � Bounded Waiting: Strong fairness - FCFS order!
• � Fairness: First-Come-First-Serve mechanism
3. HARDWARE-BASED SOLUTIONS
Ye solutions special hardware instructions use karte hain jo atomic hain (ek hi
instruction cycle mein complete hote hain).
9
// ENTRY SECTION
while(TestAndSet(&lock)) { // Jab tak lock true aa raha hai
// Matlab lock busy hai, kisi aur process ke pass hai
// Busy wait karo - dobara try karo
// while condition mein:
// TestAndSet(&lock) ko call karo
// - agar lock false tha (free tha) to true set karo aur false return karo
// while(false) = exit loop, ENTRY MILGAYA!
// - agar lock true tha (busy tha) to true rahega aur true return karo
// while(true) = continue loop, busy wait karo
}
// Jab while loop se exit ho, matlab lock acquire ho gaya!
// lock ab true hai aur sirf mera hai
// CRITICAL SECTION
printf("Process %d in CS\n", process_id);
shared_data++;
// EXIT SECTION
lock = false; // Lock ko release karo (false set karo)
// Ab dusra process pick up kar sakta hai
}
Timeline of Execution:
Scenario: P0 aur P1 dono entry le rahe hain
Time P0 P1 Lock
---- --- --- ----
1 TestAndSet(&lock)? TestAndSet(&lock)? false
Returns: false, set to true - true
2 While(false)=Exit! - true
P0 enters CS!
3 CS executing... TestAndSet(&lock)? true
4 Returns: true true
While(true)=Continue
Busy waiting...
5 CS executing... Busy waiting... true
6 CS executing... Busy waiting... true
7 lock = false (exit) Busy waiting... false
8 - TestAndSet(&lock)? false
Returns: false, set to true
While(false)=Exit!
9 - P1 enters CS! true
10
Properties:
• � Mutual Exclusion: Guaranteed by hardware atomicity
• � Works for N processes: Sabhi process queue mein wait kar sakte hain
• � Hardware backed: Atomic operation isliye race condition nahi
// ENTRY SECTION
// Jab tak lock fail na ho jaaye, try karte raho (Retry logic)
while(CompareAndSwap(&lock, 0, 1) != 0) {
// CompareAndSwap call karo:
// - lock check karo, kya 0 hai?
// - agar 0 hai to 1 set karo aur 0 return karo
// while(0 != 0) = while(false) = Exit! ENTRY MILGAYA!
// - agar 0 nahi hai (lock pehle se 1 hai) to kuch mat karo aur 1 return karo
// while(1 != 0) = while(true) = Continue, Retry karo
}
// Jab while se exit ho, matlab lock acquire hua!
// CRITICAL SECTION
11
printf("Process %d in CS\n", process_id);
shared_data++;
// EXIT SECTION
lock = 0; // Lock reset karo
}
CAS:
- Check karo aur specific value ke liye
- Agar match karo to naya value set karo
- Sab atomic hai, bohot flexible hai
- Lock-free data structures banane mein use hota hai
// ENTRY SECTION
while(key == true) { // Jab tak key true hai
Swap(&lock, &key); // Lock aur key ko swap karo
// Atomic operation se:
// - agar lock false tha to key mein false aa jayega
// aur lock true ho jayega (acquired)
12
// - agar lock true tha to key true hi rahega
// aur lock true hi rahega (still occupied)
}
// Loop exit means: lock false tha, key mein false aa gaya
// Ab lock true hai = acquired!
// CRITICAL SECTION
printf("Process %d in CS\n", process_id);
shared_data++;
// EXIT SECTION
lock = false; // Lock release karo
}
Timeline of Execution:
Scenario: P0 aur P1 entry le rahe hain
Time P0 P1 Lock
---- --- --- ----
1 Swap(&lock, &key_P0) - false
lock=true, key_P0=false
while(false)=Exit!
P0 ENTERS!
2 CS executing... Swap(&lock, &key_P1) true
lock=true, key_P1=true
while(true)=Continue
3 CS executing... Swap(&lock, &key_P1) true
lock=true, key_P1=true
while(true)=Continue
(Busy waiting)
4 lock = false (exit) Swap(&lock, &key_P1) false
lock=true, key_P1=false
while(false)=Exit!
5 - P1 ENTERS! true
4.1 SEMAPHORES
4.1.1 BINARY SEMAPHORE Type: OS Primitive (0 or 1 only)
13
Data Structure with Hinglish Comments:
// Semaphore ko represent karne ke liye
struct BinarySemaphore {
int value; // Value sirf 0 ya 1 ho sakti hai
// 0 = Resource occupied hai
// 1 = Resource available hai
Queue process_queue; // Agar resource nahi mila to yahan queue mein wait karo
};
// Check: kya queue mein koi process wait kar raha hai?
if(S->process_queue is NOT empty) {
// Haan, queue mein process hain
Process p = remove_from_queue(S->process_queue); // First process ko nikalo
wakeup(p); // Us process ko wake up karo (ready state mein daalo)
// Ab ye process ready queue mein ja jayega
}
else { // Queue empty hai
14
// Koi process wait nahi kar raha
S->value = 1; // Resource ko available mark karo (1 set karo)
// Agar next process wait() call kare to directly entry lega
}
}
// CRITICAL SECTION
// Ab sirf ek process execute karega
printf("Process %d in CS\n", process_id);
shared_data++;
// EXIT SECTION
signal(mutex); // Resource ko release karo
// Queue mein koi wait kar raha hai to wake up karo
// Nahi to [Link] = 1 set karo
// REMAINDER SECTION
do_other_work();
}
}
Key Properties:
• � Mutual Exclusion: Haan, sirf ek process CS mein
• � No Busy Waiting: Process sleep karta hai, CPU waste nahi hota
• � Fair: FIFO queue se fairness maintained
15
int value; // Koi bhi non-negative integer ho sakti hai
// value = available resources ki count
// Initially = total resources
Queue process_queue; // Wait karne wale processes
};
16
}
// Printer chahiye
wait(printers); // Ek printer request karo
// value 3->2 ho jayega
// Agar value >= 0 to printer mil jayega
// Agar value < 0 to queue mein jaao aur wait karo
Counting Semaphore:
- value 0 to N
- Multiple instances of resources
- Resource pool management
Example:
Binary: Ek bathroom - sirf ek person use kar sakta
Counting: 5 bathrooms - 5 persons ek saath use kar sakte
17
4.2 MONITORS
Type: High-level Language Construct
// Constructor
public BankAccount(int initial_balance) {
balance = initial_balance;
}
18
insufficient_funds.signal(); // Kisi ek ko wake up karo
// Jo paise ka wait kar raha tha
}
// Usage
BankAccount account = new BankAccount(1000);
Key Features:
• � Automatic Mutual Exclusion: synchronized keyword se
• � High Level: Semaphores se easier
• � Condition Variables: wait(), signal(), signal_all()
• � No Manual Locking: Compiler handle karta hai
19
void mutex_acquire(Mutex *m) {
// Atomic operation
while(m->locked == true) {
// Mutex locked hai, wait karo
// Busy waiting ya OS se sleep kar sakte ho
}
// CRITICAL SECTION
// Ab sirf ek thread yahan hai
printf("Process %d in CS\n", process_id);
shared_resource++;
// EXIT SECTION
mutex_release(&lock); // Lock release karo
// Ab dusra thread acquire kar sakta hai
}
BINARY SEMAPHORE:
- Ownership concept nahi
20
- Koi bhi process signal kar sakta hai
- Flexible, signaling mechanism bhi hai
- General purpose synchronization
BoundedBuffer b;
[Link] = 0; // Pointer - shuru se start
[Link] = 0; // Pointer - shuru se start
// SEMAPHORES
Semaphore mutex = 1; // Mutual exclusion - buffer ko protect karne ke liye
Semaphore empty = 10; // Empty slots ki count (BUFFER_SIZE = 10)
// Initially 10 slots empty hain
Semaphore full = 0; // Filled slots ki count
// Initially 0 slots filled hain
21
// ACQUIRE MUTUAL EXCLUSION
wait(mutex); // Buffer ko exclusively access karne ke liye
// mutex = 1 -> 0
// Ab sirf ye producer buffer access kar sakta hai
// ADD TO BUFFER
[Link][[Link]] = item; // Produced item ko buffer mein add karo
[Link] = ([Link] + 1) % BUFFER_SIZE; // Next position mein ja (circular)
// SIGNAL FULL
signal(full); // Buffer mein ab ek filled slot add hua
// full = 0 -> 1 (consumer ko signal karo)
}
}
// SIGNAL EMPTY
signal(empty); // Buffer mein ab ek empty slot add hua
// empty ko increment karo
// Agar producer wait kar raha tha to wake up ho jayega
22
// CONSUME ITEM
consume_item(item); // Item ko use karo
}
}
Key Points:
• � 3 Semaphores: mutex (exclusion), empty (slots), full (items)
• � Order Important: empty pehle, phir mutex, phir full
• � Deadlock Prevention: Order aur signaling carefully designed
• � Circular Buffer: (pointer + 1) % SIZE se wrap around
23
// SHARED RESOURCES
int read_count = 0; // Kitne readers currently reading hain
// SEMAPHORES
Semaphore write_lock = 1; // Writers ke liye - exclusive access
// agar 1 to writer enter kar sakta
// agar 0 to writer wait karega
Semaphore read_count_lock = 1; // read_count ko protect karne ke liye
// read_count shared resource hai
if(read_count == 1) {
// Pehla reader - writers ko block karo
wait(write_lock); // Write_lock acquire karo
// Isse writers block ho jayenge
}
// READ SECTION
printf("Reader %d is reading\n", reader_id);
read_data(); // Data ko read karo
// EXIT SECTION
if(read_count == 0) {
// Aakhri reader - writers ko unblock karo
signal(write_lock); // Write_lock release karo
24
// Ab writers entry le sakte hain
}
// EXIT SECTION
25
Writer waiting...
7 Reader1 exit:
wait(read_count_lock) 2 0
read_count-- 1 0
if(count==0) nahi 1 0
signal(read_count_lock) 1 0
8 Reader2 exit:
wait(read_count_lock) 1 0
read_count-- 0 0
if(count==0) YES!
signal(write_lock) 0 1 (Writer unblocked!)
signal(read_count_lock) 0 1
9 Writer proceed
write_lock already locked by writer
*/
Semaphore write_lock = 1;
Semaphore read_lock = 1; // EXTRA: read_count access ke liye
Semaphore read_count_lock = 1;
Semaphore write_count_lock = 1; // EXTRA: write_count ko protect kare
while(1) {
wait(read_lock); // EXTRA: Check karo agar writer wait kar raha
wait(read_count_lock);
read_count++;
if(read_count == 1)
wait(write_lock);
signal(read_count_lock);
signal(read_lock);
// READ
read_data();
wait(read_count_lock);
26
read_count--;
if(read_count == 0)
signal(write_lock);
signal(read_count_lock);
}
}
// WRITE
write_data();
signal(write_lock);
wait(write_count_lock); // EXTRA
write_count--; // EXTRA
if(write_count == 0) // EXTRA: Aakhri writer
signal(read_lock); // EXTRA: Readers ko allow karo
signal(write_count_lock); // EXTRA
}
}
27
// HUNGRY - Eating ke liye chopsticks chahiye
// EATING SECTION
eat(); // Dono chopsticks mein khana kha raha hai
Time P0 P1 P2 P3 P4
---- --- --- --- --- ---
1 think() think() think() think() think()
DEADLOCK!
Sabhi philosophers apna left chopstick pakde hain
Sabhi apna right chopstick ke liye wait kar rahe hain
Circular waiting! Koi bhi proceed nahi kar sakta!
*/
28
// SHARED RESOURCES
Semaphore chopstick[5] = {1,1,1,1,1};
// EATING
eat(); // Ab khana kha sakta hai
/*
Timeline:
T1: P0(even) take chop[0] P1(odd) take chop[1]
T2: P0 wait chop[1] - BLOCKED P1 take chop[0]
P1 eat() - P0 wait ho gaya to P1 freely eat kar sakta
T3: P1 release both P0 ab take chop[1], phir chop[0]
T4: P0 eat() P2 start thinking
29
// ===== PHILOSOPHER i KA CODE =====
void philosopher(int i) {
while(1) {
think();
wait(chopstick[i]); // Left
wait(chopstick[(i+1) % 5]); // Right
signal(chopstick[i]); // Return
signal(chopstick[(i+1) % 5]);
eat();
signal(chopstick[i]);
signal(chopstick[(i+1) % 5]);
}
}
30
5.4 SLEEPING BARBER PROBLEM
Description: Barber, 1 cutting chair, N waiting chairs.
// SHARED RESOURCES
int waiting_count = 0; // Kitne customers waiting hain
// SEMAPHORES
Semaphore customers = 0; // Customers ki count (barber ke liye signal)
// 0 = koi customer nahi
// >0 = customers waiting
Semaphore barbers = 0; // Barbers ki count (customer ke liye signal)
// 0 = barber occupied
// 1 = barber free
Semaphore mutex = 1; // waiting_count ko protect karne ke liye
// HAIRCUT DO
cut_hair(); // Barber apna kaam kar raha hai
}
}
31
wait(barbers); // Barber ke ready hone ka wait karo
// HAIRCUT LELO
get_haircut(); // Apna haircut le raha hai
}
else { // Sab chairs full hain
signal(mutex); // Kuch nahi, just release
leave(); // Saloon se bahar niklo (frustrated!)
}
}
2 SLEEPING... wait(mutex) -
waiting_count++, 1 -
3 - signal(customers) wait(mutex)
signal(mutex) WAIT...
- -
4 Signal wakes barber wait(barbers) -
wait(customers)=WAKE! WAITING... -
waiting_count--=0 - -
5 signal(barbers) GET HAIRCUT! -
signal(mutex) - -
6 - - wait(mutex)
waiting_count++, 1
7 cut_hair()... - signal(customers)
signal(mutex)
8 - - wait(barbers)
-
9 signal(customers)=OK - WAKE UP! GET HAIRCUT!
(No one waiting) - -
GO BACK TO SLEEP! - -
32
5.5 CIGARETTE SMOKERS PROBLEM
Description: 3 smokers (tobacco, paper, match hain), 1 agent. Agent provides
2 items, smoker with 3rd combines aur smokes.
Challenge:
Main Problem:
- Agent produces 2 random items
- Smoker with 3rd item le sakta hai
- BUT: Smoker agent ko signal nahi kar sakte "kya available hai?"
- Agent sirf signal kar sakta hai, pehle nahi pata ki kya chahiye
// Pushers ke semaphores
int tobaccoPusherSem = 0; // Tobacco+paper ->match smoker
int paperPusherSem = 0; // Tobacco+match ->paper smoker
int matchPusherSem = 0; // Paper+match ->tobacco smoker
33
signal(tobaccoPusherSem); // Pusher ko inform karo
}
else if(choice == 1) { // Tobacco aur Match
signal(tobaccoSem);
signal(matchSem);
signal(paperPusherSem); // Paper smoker ko pusher call karega
}
else { // Paper aur Match
signal(paperSem);
signal(matchSem);
signal(matchPusherSem); // Match smoker ko pusher call karega
}
}
}
smoke();
signal(agentSem);
}
34
}
smoke();
signal(agentSem);
}
}
wait(tobaccoSem); // Tobacco le lo
wait(paperSem); // Paper le lo
wait(tobaccoSem); // Tobacco le lo
wait(matchSem); // Match le lo
wait(paperSem); // Paper le lo
35
wait(matchSem); // Match le lo
Process continues...
Key Insight:
Ye problem ka solution hai PUSHERS.
Pushers agent ke behalf mein kaam karte hain.
Woh items combine karte hain aur sahi smoker ko signal karte hain.
Ye mechanism "monitor" approach se bhi kar sakte hain.
// Example:
Bank_balance = 1000;
36
// Process P0 aur P1 dono +100 ka transaction karte hain
37
// Meaning: Process indefinite wait nahi karega
// Max X times other processes enter kar sakte hain tab apne turn aayega
7. SUMMARY TABLE
All Algorithms Comparison
38
Medium Priority (��):
• Dining Philosophers
• Dekker’s Algorithm
• Hardware solutions (TSL, CAS)
• Monitors
// Dining Philosophers
Right chopstick: (i + 1) % N
END OF DOCUMENT
Remember: Concepts samjhna zaroori hai, formulas yaad karna nahi. Har
algorithm ke “kyun?” ko samjho.
39
Good Luck for GATE 2026! �
Document with Complete Hinglish Comments Every Line Explained All Algo-
rithms Covered Last Updated: November 2025
40