← Computer Science notes

Unit 2 · Operating Systems

Chapters 3, 5 · Process Synchronization, Semaphores & Virtual Memory

pdcampus.in
pdcampus.in • DSSSB TGT CS
Beginner Topper
OS Sync, Semaphores, Segmentation, VM Unit 5 • Ch 2 • Race Condition Critical Section Peterson, Semaphores Counting Binary Producer Consumer, Segmentation Base Limit, Virtual Memory Demand Paging Thrashing
Beginner Story Mode Complete Notes

Imagine 2 cooks in same kitchen sharing same salt jar. Both need to add salt same time. Cook A reads salt level, Cook B also reads same level, both add salt, one addition lost! That's Race Condition when 2 processes access shared variable count++ simultaneously lost update because count++ is 3 steps read-modify-write not atomic.

To avoid race we need Critical Section section of code where shared variable accessed. Only one process can be in critical section at a time. Requirements: Mutual Exclusion only one in CS at a time, Progress if no process in CS, decision which enters CS cannot be postponed indefinitely, Bounded Waiting bound on number of times other processes allowed to enter after a process requests entry no starvation.

Peterson's solution for 2 processes uses flag and turn variables software solution satisfies all 3. Hardware solutions TestAndSet atomic instruction returns old value and sets to 1 atomic, CompareAndSwap. But busy waiting wastes CPU.

Semaphore = integer variable S accessed via wait() P() and signal() V() atomic operations invented by Dijkstra. Binary semaphore 0/1 mutex lock, Counting semaphore 0→N resource instances tracks count of available resources. wait() S=S-1 if S<0 block process & add to wait queue put to sleep until semaphore available signal() S=S+1 if waiting processes→wake up one process. Solves classic problems: Producer-Consumer bounded buffer finite capacity uses empty full mutex semaphores producers wait if FULL consumers wait if EMPTY, Readers-Writers multiple readers can read simultaneously writers require exclusive access readers priority→writers may starve, Dining Philosophers 5 philosophers 5 chopsticks each needs 2 chopsticks to eat→potential deadlock.

Segmentation = User view program as segments Code holds instructions base=1000 limit=400 Data variables/globals base=5000 limit=200 Heap dynamic allocations base=6000 limit=500 Stack function calls/locals base=9000 limit=300. Segment Table Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300. Translation Logical address=+ Physical address=base+offset if offset
Virtual Memory = Execution of process not completely in memory only bring needed pages demand paging page fault trap to OS find frame swap in restart. Benefits large programs can run even if larger than physical memory multiprogramming degree increases. Thrashing diagram CPU utilization vs degree of multiprogramming rises then falls due to thrashing too many page faults. Working Set model and Page Fault Frequency control thrashing. Copy on Write fork optimization child shares parent pages until write then copy Memory mapped files map file to memory. Kernel memory allocation buddy system slab allocator. Let's learn with handwritten diagrams.

1. Process Synchronization - Critical Section & Race
Process Synchronization Critical Section handwritten
Fig 1: Race Condition when 2 processes access shared variable count++ simultaneously lost update Example count=10 P1 reads 10 P2 reads 10 P1 adds 1 writes 11 P2 adds 1 writes 11 final 11 should be 12 lost update count++ is 3 steps read-modify-write not atomic | Critical Section requirements Mutual Exclusion only one in CS at a time Progress if no process in CS decision which enters cannot be postponed indefinitely Bounded Waiting bound on number of times other allowed to enter after a process requests entry no starvation | Solutions Peterson's solution for 2 processes flag[0] flag[1] turn variable software solution satisfies all 3 flags indicate interest turn indicates whose turn busy waiting but satisfies TestAndSet hardware atomic instruction returns old value and sets to 1 atomic while TestAndSet(lock) busy wait critical section lock=false CompareAndSwap similar atomic | Summary Race condition leads to inconsistent data Need synchronization to protect critical section

Race Condition: When 2 processes access shared variable count++ simultaneously lost update. Example count=10 initially. P1 reads count 10, P2 reads count 10 (same time), P1 adds 1 →11 writes 11, P2 adds 1 →11 writes 11. Final 11 should be 12! One update lost. Because count++ is 3 steps: 1) read count from memory to register, 2) increment register, 3) write back to memory. Not atomic can be interleaved.

Critical Section Problem:
- Each process has entry section, critical section, exit section, remainder section.
- Structure: do { entry section → critical section → exit section → remainder section } while(true)
- Requirements 3 must satisfy:
- Mutual Exclusion: If process Pi is executing in its critical section then no other processes can be executing in their critical sections only one in CS at a time.
- Progress: If no process is executing in its critical section and some processes wish to enter their critical sections then selection of process that will enter CS next cannot be postponed indefinitely only processes not in remainder can participate decision cannot be postponed.
- Bounded Waiting: Bound on number of times other processes are allowed to enter their critical sections after a process has made request to enter its critical section and before request is granted no starvation.

Solutions:
- Peterson's Solution for 2 processes P0 and P1: Software solution uses flag[2] and turn. flag[i]=true indicates Pi wants to enter CS turn indicates whose turn to enter. Algorithm P0: flag[0]=true turn=1 while(flag[1] && turn==1) busy wait // entry, CS, flag[0]=false // exit. P1 similar flag[1]=true turn=0 while(flag[0] && turn==0) busy wait. Satisfies all 3 mutual exclusion progress bounded waiting. Disadvantage busy waiting wastes CPU cycles spinlock.
- TestAndSet hardware instruction: Atomic instruction boolean TestAndSet(boolean *target) { boolean rv=*target; *target=true; return rv; } Atomic means indivisible cannot be interrupted. Solution: shared boolean lock=false initially. Pi: while(TestAndSet(&lock)) ; // busy wait CS lock=false // exit. Ensures mutual exclusion progress but bounded waiting not guaranteed may starve. Hardware support needed.
- CompareAndSwap: Similar atomic CAS(int *value, int expected, int new_value) atomically compares *value with expected if equal sets to new_value returns old *value. Used to implement locks.
- Disadvantages of busy waiting solutions waste CPU cycles spinlock when waiting process loops continuously checking condition.
- Solution blocking using semaphores instead of busy waiting.

Race Condition 2 processes access shared count++ simultaneously lost update count=10 P1 reads 10 P2 reads 10 P1 writes 11 P2 writes 11 final 11 should be 12 count++ read-modify-write 3 steps not atomic | Critical Section entry CS exit remainder 3 Requirements Mutual Exclusion only one in CS at a time Progress if no process in CS decision cannot be postponed indefinitely Bounded Waiting bound on number of times other allowed to enter after request no starvation | Solutions Peterson's for 2 processes flag turn flag[i]=true interest turn whose turn busy waiting satisfies all 3 TestAndSet atomic returns old sets to 1 while(TestAndSet(&lock)) busy wait CS lock=false CompareAndSwap atomic CAS busy waiting wastes CPU spinlock
2. Semaphores - Counting & Binary - Synchronization Tool
Semaphores Counting Binary handwritten
Fig 2: Semaphores Definition semaphore = integer variable S accessed via wait() P() and signal() V() atomic operations indivisible no race condition Purpose synchronize processes/threads to avoid race conditions | Binary semaphore = 0/1 (mutex lock) S is only 0 or 1 Used as a lock/mutex for mutual exclusion 1=unlocked/free 0=locked/held | Counting semaphore = 0→N (resource instances) S can range 0...N N=number of available resources Tracks count of available resources/instances | wait() = P() [down] S=S-1 if S<0→block the process & add it to the wait queue process is put to sleep until semaphore is available | signal() = V() [up] S=S+1 if there are waiting processes→wake up one process | Classic problems 1) Producer-Consumer bounded buffer finite capacity buffer Producers wait if buffer is FULL Consumers wait if buffer is EMPTY Uses empty full mutex semaphores 2) Readers-Writers Multiple readers can read simultaneously Writers require exclusive access Readers priority→writers may suffer starvation 3) Dining Philosophers 5 philosophers 5 chopsticks Each needs 2 chopsticks to eat→potential deadlock | Implementation Busy waiting (spinlock) busy loop while S≤0 wastes CPU cycles Blocking process sleeps added to queue woken by signal()→efficient Note P()=proberen (to test) V()=verhogen (to increment) classic OS terminology

Definition: Semaphore = integer variable S accessed via only two atomic operations wait() P() and signal() V() indivisible no race condition. Invented by Dijkstra. Purpose synchronize processes/threads to avoid race conditions.
- P() = proberen Dutch to test, V() = verhogen Dutch to increment classic OS terminology.

Binary semaphore = 0/1 (mutex lock):
- S is only 0 or 1.
- Used as a lock/mutex for mutual exclusion.
- 1 = unlocked/free, 0 = locked/held.
- Initial value 1. Process enters CS does wait(S) if S=1 becomes 0 enters if S=0 blocked. Exit does signal(S) S becomes 1 wakes waiting.

Counting semaphore = 0→N (resource instances):
- S can range 0...N (N=number of available resources/instances).
- Tracks count of available resources/instances e.g., 3 printers S=3.
- Initial S=N. Each allocation wait() decrements S, each release signal() increments.

wait() = P() [down] operation:
- S = S -1
- if S <0 → block the process & add it to the wait queue.
- Process is put to sleep until semaphore is available blocked not busy waiting in blocking implementation.
- Pseudo: wait(S) { S--; if(S<0) { add process to queue; block(); } } atomic.

signal() = V() [up] operation:
- S = S +1
- if there are waiting processes → wake up one process remove from queue wakeup().
- Pseudo: signal(S) { S++; if(S<=0) { remove process from queue; wakeup(P); } } atomic.
- Note: If S<0 number of waiting processes = |S|. If S<=0 after increment there were waiting processes.

Classic Problems Solved by Semaphores:
- 1) Producer-Consumer Bounded Buffer: Bounded buffer finite capacity buffer size N. Producers produce items consumers consume. Producers wait if buffer is FULL Consumers wait if buffer is EMPTY. Uses 3 semaphores: empty = N initially count of empty slots, full =0 initially count of full slots, mutex=1 binary semaphore for mutual exclusion on buffer. Producer: wait(empty) wait(mutex) produce item to buffer signal(mutex) signal(full). Consumer: wait(full) wait(mutex) consume item from buffer signal(mutex) signal(empty). Order of wait matters to avoid deadlock wait(empty) before wait(mutex) else deadlock possible.
- 2) Readers-Writers: Multiple readers can read simultaneously but writers require exclusive access no readers or writers while writing. Readers priority → writers may suffer starvation if readers keep arriving writer waits long. Solutions readers-preference, writers-preference, fair. Uses mutex and wrt semaphore readcount variable.
- 3) Dining Philosophers: 5 philosophers 5 chopsticks arranged in circle each needs 2 chopsticks to eat left and right. Potential deadlock if each holds left chopstick and waits for right circular wait. Solutions: allow only 4 philosophers to eat at a time counting semaphore 4, or odd philosopher picks left first even picks right first breaking circular wait, or use monitor.

Implementation:
- Busy waiting (spinlock): busy loop while S ≤0 checks repeatedly wastes CPU cycles but no context switch overhead good for short waits multiprocessor.
- Blocking: process sleeps added to queue woken by signal() → efficient no CPU waste while waiting needs context switch.
- Semaphores can be used for both mutual exclusion binary and resource counting counting.

Definition semaphore = integer variable S accessed via wait() P() and signal() V() atomic operations indivisible no race Purpose synchronize processes/threads to avoid race | Binary semaphore = 0/1 (mutex lock) S only 0 or 1 Used as lock/mutex mutual exclusion 1=unlocked/free 0=locked/held | Counting semaphore = 0→N (resource instances) S range 0...N N=number available resources Tracks count | wait() = P() [down] S=S-1 if S<0→block process & add to wait queue put to sleep until available | signal() = V() [up] S=S+1 if waiting→wake up one process | Classic 1) Producer-Consumer bounded buffer finite capacity Producers wait if FULL Consumers wait if EMPTY Uses empty full mutex 2) Readers-Writers Multiple readers can read simultaneously Writers exclusive Readers priority→writers starvation 3) Dining Philosophers 5 philosophers 5 chopsticks Each needs 2→potential deadlock | Implementation Busy waiting spinlock busy loop while S≤0 wastes CPU Blocking process sleeps added to queue woken by signal→efficient Note P()=proberen V()=verhogen classic
3. Segmentation - Logical Division - User View
Segmentation Logical Division handwritten
Fig 3: Segmentation User view program as segments Code holds instructions base=1000 limit=400 Data variables/globals base=5000 limit=200 Heap dynamic allocations base=6000 limit=500 Stack function calls/locals base=9000 limit=300 → Segment Table Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 | Segmentation Translation Logical address=+ Physical address=base+offset if offset

Segmentation: User view program as logical segments not just pages. Program naturally divided into segments: Code holds instructions, Data variables/globals, Heap dynamic allocations, Stack function calls/locals each has different purpose and size. Unlike paging which is fixed size and no logical meaning segmentation matches programmer's view.

- Example: Code base=1000 limit=400 means code segment starts at physical address 1000 and length 400 bytes, Data base=5000 limit=200, Heap base=6000 limit=500, Stack base=9000 limit=300.
- Segment Table: Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 per process segment table.

Segmentation Translation:
- Logical address = + e.g., segment 0 offset 100 means 100th byte of code segment.
- Physical address = base + offset if offset < limit else → TRAP (segmentation fault) protection.
- Example: Logical address segment 0 offset 100 base 1000 limit 400 offset 100 <400 valid physical =1000+100=1100. If offset 500 offset 500 ≥400 invalid → trap segmentation fault (segfault).
- Each segment has limit to prevent accessing beyond segment protection.

Advantages of Segmentation:
- Logical view → program sees segments naturally code/data/stack/heap matches programming structure.
- Protection → each segment has its own base/limit perms read/write/execute e.g., code segment read-only execute-only data read-write.
- Sharing → segments can be shared between processes e.g., shared library code segment shared among processes.
- Variable size → segments grow/shrink as needed e.g., heap can grow stack can grow.

vs Paging Comparison:
- Paging: Fixed size blocks = pages e.g., 4KB, No logical division → just page# arbitrary division, Internal fragmentation possible last page may not fully used but small.
- Segmentation: Variable size segments, Logical → matches program structure code/data/stack/heap, External fragmentation possible as variable size leaves holes free memory fragmented need compaction.

Segmented Paging (Combined):
- To get benefits of both, Segment is divided into pages. Segment 2 split into multiple Pages Page0 Page1 Page2.
- Logical address = segment number + page number + offset. Segment table points to page table page table points to frames.
- ⇒ Get benefits of both: logical segments + paging for memory management.
- Why use it? Reduces external frag vs pure segmentation, allows shared/logical view. Used in Intel x86 architecture segmentation + paging.
- Disadvantage needs two-level translation segment table + page table overhead more memory accesses TLB helps.

Segmentation User view program as segments Code holds instructions base=1000 limit=400 Data variables/globals base=5000 limit=200 Heap dynamic allocations base=6000 limit=500 Stack function calls/locals base=9000 limit=300 → Segment Table Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 | Translation Logical address=+ Physical address=base+offset if offset
4. Virtual Memory - Demand Paging & Thrashing Control
Virtual Memory Demand Paging Thrashing handwritten
Fig 4: Virtual Memory Execution of process not completely in memory only bring needed pages demand paging page fault Benefits large programs can run larger than physical memory degree of multiprogramming increases | Demand Paging only bring page into memory when needed page fault handling Steps 1 Trap to OS page fault 2 Find free frame or victim 3 Swap in page from disk to frame 4 Update page table valid bit 5 Restart instruction Effective Access Time EAT = (1-p)*memory_access + p*page_fault_time p=page fault rate page fault time 10ms memory 100ns EAT high if p high | Thrashing diagram CPU utilization vs degree of multiprogramming Curve rises then falls due to thrashing Too many page faults CPU spends more time swapping than executing Working Set model keep working set of process in memory Page Fault Frequency control thrashing if faults high increase frames if faults low decrease frames | Copy on Write fork optimization child shares parent pages until write then copy on write Memory mapped files map file to memory address space Kernel memory allocation buddy system power of 2 blocks slab allocator caches for kernel objects

Virtual Memory Concept: Execution of process not completely in memory only bring needed pages into memory when needed demand paging. Allows large programs to run even if larger than physical memory degree of multiprogramming increases CPU utilization improves because more processes can be in memory partially.

Benefits:
- Large programs can run larger than physical memory only needed parts in memory.
- Degree of multiprogramming increases more processes can be kept in memory partially.
- Less I/O needed to load entire process faster process creation.
- Shared memory processes can share pages.

Demand Paging:
- Only bring page into memory when needed page referenced and not in memory page fault occurs.
- Page fault handling Steps: 1) Trap to OS page fault interrupt 2) OS finds free frame or selects victim page to replace using replacement algorithm 3) Swap in page from disk backing store to frame if victim dirty write back to disk 4) Update page table valid bit frame number 5) Restart instruction that caused fault.
- Valid bit in page table indicates if page in memory (valid) or on disk (invalid) but legal.
- Page fault rate p probability of page fault. Effective Access Time EAT = (1-p)*memory_access + p*page_fault_time. memory_access ~100ns page_fault_time ~10ms 10,000,000ns includes disk I/O. If p=0.001 (1 fault per 1000 accesses) EAT =0.999*100 +0.001*10,000,000 =99.9 +10,000=10,099.9ns high! So p must be very low for good performance need good replacement and locality.

Thrashing:
- Diagram CPU utilization vs degree of multiprogramming curve rises initially more processes higher utilization then falls sharply due to thrashing.
- Too many page faults CPU spends more time swapping pages than executing processes.
- Caused when degree of multiprogramming too high working set of all processes exceeds physical memory each process has too few frames keeps faulting.
- Effects low CPU utilization high paging activity.
- Control thrashing:
- Working Set Model: Keep working set of each process in memory working set is set of pages process has used in last Δ time window Δ working set window. If sum of working sets of all processes > physical memory reduce multiprogramming suspend a process. Ensures each process has enough frames to keep its working set.
- Page Fault Frequency PFF: Control thrashing based on page fault rate. If page fault rate of a process high → need more frames allocate more frames. If fault rate low → too many frames may reduce frames. Keep fault rate between lower and upper bounds.

Other Concepts:
- Copy on Write COW: Fork optimization child process shares parent pages initially read-only until write occurs then copy on write creates copy only when written saves memory fast fork. Example fork() child shares parent's pages marked COW when child or parent writes trap copy page then write.
- Memory Mapped Files: Map file to memory address space file I/O via memory accesses instead of read/write system calls convenient sharing.
- Kernel Memory Allocation: Buddy system allocates blocks of size power of 2 splits and merges buddies coalescing, Slab allocator caches for kernel objects frequently allocated objects like inode task_struct slabs pre-allocated efficient no fragmentation.
- Demand paging with copy on write and memory mapped files are modern VM techniques.

Virtual Memory execution not completely in memory only needed pages demand paging page fault Benefits large programs larger than physical degree multiprogramming increases less I/O shared memory | Demand Paging only bring page when needed page fault Steps 1 Trap to OS page fault 2 Find free frame or victim 3 Swap in page from disk to frame 4 Update page table valid bit 5 Restart instruction EAT = (1-p)*memory_access + p*page_fault_time p=page fault rate memory ~100ns fault time ~10ms p must be very low Example p=0.001 EAT=0.999*100+0.001*10,000,000=99.9+10,000=10,099.9ns high | Thrashing diagram CPU utilization vs degree multiprogramming rises then falls due to thrashing Too many faults CPU swapping more than executing degree too high working set exceeds memory Effects low CPU high paging | Control Working Set Model keep working set in memory set of pages used in last Δ window Δ working set window If sum working sets > physical reduce multiprogramming suspend Page Fault Frequency PFF if faults high increase frames if low decrease frames Keep between bounds | Other Copy on Write COW fork optimization child shares parent pages until write then copy Memory mapped files map file to memory Kernel memory buddy system power of 2 blocks slab allocator caches for kernel objects
5. DSSSB Traps & PYQ Practice
  • Q: Race Condition? → When 2 processes access shared variable count++ simultaneously lost update Example count=10 P1 reads 10 P2 reads 10 P1 writes 11 P2 writes 11 final 11 should be 12 lost update count++ read-modify-write 3 steps not atomic
  • Q: Critical Section? → Section of code where shared variable accessed entry CS exit remainder do { entry → CS → exit → remainder } while(true)
  • Q: Critical Section requirements 3? → Mutual Exclusion only one in CS at a time Progress if no process in CS decision which enters cannot be postponed indefinitely only not in remainder can participate Bounded Waiting bound on number of times other allowed to enter after request no starvation
  • Q: Peterson's solution? → For 2 processes P0 P1 flag[2] turn flag[i]=true indicates Pi wants to enter turn whose turn Algorithm P0 flag[0]=true turn=1 while(flag[1] && turn==1) busy wait CS flag[0]=false Satisfies all 3 mutual exclusion progress bounded waiting Disadvantage busy waiting wastes CPU spinlock
  • Q: TestAndSet? → Hardware atomic boolean TestAndSet(boolean *target) { boolean rv=*target; *target=true; return rv; } Atomic indivisible Solution shared lock=false initially Pi while(TestAndSet(&lock)) ; busy wait CS lock=false Ensures mutual exclusion progress but not bounded waiting may starve Hardware support
  • Q: CompareAndSwap? → CAS(value, expected, new_value) atomically compares *value with expected if equal sets to new_value returns old *value Used to implement locks atomic
  • Q: Semaphore definition? → Integer variable S accessed via wait() P() and signal() V() atomic operations indivisible no race Purpose synchronize processes/threads to avoid race conditions Dijkstra P=proberen to test V=verhogen to increment
  • Q: Binary semaphore? → 0/1 mutex lock S only 0 or 1 Used as lock/mutex mutual exclusion 1=unlocked/free 0=locked/held Initial 1 wait if 1→0 enters if 0 blocked signal S→1 wakes
  • Q: Counting semaphore? → 0→N resource instances S range 0...N N=number available resources Tracks count e.g., 3 printers S=3 Initial N Each wait decrements Each signal increments
  • Q: wait() P() down? → S=S-1 if S<0→block process & add to wait queue put to sleep until available Pseudo wait(S) { S--; if(S<0) { add to queue; block(); } } atomic If S<0 number waiting =|S|
  • Q: signal() V() up? → S=S+1 if waiting processes→wake up one remove from queue wakeup() Pseudo signal(S) { S++; if(S<=0) { remove from queue; wakeup(P); } } atomic
  • Q: Producer-Consumer? → Bounded buffer finite capacity N Producers wait if FULL Consumers wait if EMPTY Uses 3 semaphores empty=N initially count empty slots full=0 initially count full slots mutex=1 binary mutual exclusion on buffer Producer wait(empty) wait(mutex) produce to buffer signal(mutex) signal(full) Consumer wait(full) wait(mutex) consume from buffer signal(mutex) signal(empty) Order matters wait(empty) before wait(mutex) to avoid deadlock
  • Q: Readers-Writers? → Multiple readers can read simultaneously Writers exclusive access no readers or writers while writing Readers priority→writers may suffer starvation if readers keep arriving writer waits long Solutions readers-preference writers-preference fair Uses mutex and wrt semaphore readcount variable
  • Q: Dining Philosophers? → 5 philosophers 5 chopsticks circle each needs 2 chopsticks to eat left and right Potential deadlock if each holds left waits for right circular wait Solutions allow only 4 to eat at a time counting semaphore 4 or odd picks left first even picks right first breaking circular wait or use monitor
  • Q: Implementation busy vs blocking? → Busy waiting spinlock busy loop while S≤0 wastes CPU but no context switch good for short waits multiprocessor Blocking process sleeps added to queue woken by signal→efficient no CPU waste while waiting needs context switch
  • Q: Segmentation? → User view program as segments Code holds instructions base=1000 limit=400 Data variables/globals base=5000 limit=200 Heap dynamic allocations base=6000 limit=500 Stack function calls/locals base=9000 limit=300 Each segment different purpose size
  • Q: Segment Table? → Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 per process segment table
  • Q: Segmentation Translation? → Logical address=+ Physical=base+offset if offset
  • Q: Advantages Segmentation? → Logical view program sees segments naturally code/data/stack/heap matches programming structure Protection each segment own base/limit perms read/write/execute e.g., code read-only execute Data read-write Sharing segments can be shared between processes e.g., shared library code Variable size segments grow/shrink as needed heap stack grow
  • Q: Paging vs Segmentation? → Paging Fixed size blocks pages e.g., 4KB No logical division just page# arbitrary Internal fragmentation possible small vs Segmentation Variable size segments Logical matches program structure code/data/stack/heap External fragmentation possible variable size leaves holes need compaction
  • Q: Segmented Paging? → Benefits of both Segment is divided into pages Logical=segment number+page number+offset Segment table→page table→frames Get benefits logical segments + paging for memory management Why use? Reduces external frag vs pure segmentation allows shared/logical view Intel x86 uses segmentation+paging Disadvantage two-level translation overhead TLB helps
  • Q: Virtual Memory? → Execution of process not completely in memory only needed pages demand paging Allows large programs larger than physical memory degree multiprogramming increases less I/O faster creation shared memory processes can share pages
  • Q: Demand Paging? → Only bring page when needed page referenced not in memory page fault handling Steps 1 Trap to OS page fault 2 Find free frame or victim replacement algorithm 3 Swap in page from disk backing store to frame if victim dirty write back 4 Update page table valid bit frame 5 Restart instruction Valid bit indicates if page in memory valid or on disk invalid but legal Page fault rate p probability Effective Access Time EAT=(1-p)*memory_access + p*page_fault_time memory ~100ns fault ~10ms p must be very low Example p=0.001 EAT=0.999*100+0.001*10,000,000=99.9+10,000=10,099.9ns high
  • Q: Thrashing? → Diagram CPU utilization vs degree of multiprogramming rises then falls due to thrashing Too many page faults CPU spends more time swapping than executing degree too high working set exceeds memory Effects low CPU high paging
  • Q: Control thrashing Working Set? → Keep working set in memory set of pages used in last Δ window Δ working set window If sum working sets > physical reduce multiprogramming suspend Ensures each process enough frames Working Set Model
  • Q: PFF? → Page Fault Frequency control thrashing If fault rate high→need more frames allocate more If low→too many frames may reduce Keep between lower and upper bounds
  • Q: COW? → Copy on Write fork optimization child shares parent pages read-only until write then copy on write creates copy only when written saves memory fast fork Example fork child shares parent pages marked COW when child or parent writes trap copy page then write
  • Q: Memory mapped files? → Map file to memory address space file I/O via memory accesses instead of read/write convenient sharing
  • Q: Kernel memory allocation? → Buddy system power of 2 blocks splits merges buddies coalescing Slab allocator caches for kernel objects frequently allocated objects like inode task_struct slabs pre-allocated efficient no fragmentation
Race Condition 2 processes access shared count++ simultaneously lost update count=10 P1 reads 10 P2 reads 10 P1 writes 11 P2 writes 11 final 11 should be 12 count++ read-modify-write 3 steps not atomic | Critical Section entry CS exit remainder 3 Requirements Mutual Exclusion only one in CS Progress if no process in CS decision cannot be postponed Bounded Waiting bound after request no starvation | Peterson's for 2 flag turn flag[i]=true interest turn whose turn busy waiting satisfies all 3 TestAndSet atomic returns old sets to 1 while(TestAndSet(&lock)) busy wait CS lock=false CompareAndSwap atomic CAS | Semaphore integer variable S accessed via wait() P() and signal() V() atomic indivisible no race Purpose synchronize processes/threads avoid race Dijkstra P=proberen V=verhogen | Binary 0/1 mutex lock S only 0 or 1 Used as lock/mutex 1=unlocked/free 0=locked/held Initial 1 | Counting 0→N resource instances S range 0...N N=number available Tracks count e.g., 3 printers S=3 Initial N | wait() P() down S=S-1 if S<0→block & add to wait queue put to sleep | signal() V() up S=S+1 if waiting→wake up one remove queue | Classic 1) Producer-Consumer bounded buffer finite N Producers wait if FULL Consumers wait if EMPTY Uses empty=N full=0 mutex=1 Producer wait(empty) wait(mutex) produce signal(mutex) signal(full) Consumer wait(full) wait(mutex) consume signal(mutex) signal(empty) Order wait(empty) before wait(mutex) avoid deadlock 2) Readers-Writers Multiple readers can read simultaneously Writers exclusive Readers priority→writers starvation readers-preference writers-preference fair mutex wrt readcount 3) Dining Philosophers 5 philosophers 5 chopsticks Each needs 2→deadlock Solutions allow only 4 counting semaphore 4 odd left first even right first break circular wait monitor | Implementation Busy waiting spinlock busy loop while S≤0 wastes CPU no context switch good short waits multiprocessor Blocking sleeps added to queue woken by signal efficient no waste needs context switch | Segmentation User view program as segments Code base=1000 limit=400 Data base=5000 limit=200 Heap base=6000 limit=500 Stack base=9000 limit=300 Each different purpose size | Segment Table Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 per process | Translation Logical=+ Physical=base+offset if offset physical reduce multiprogramming suspend Ensures each enough frames PFF Page Fault Frequency if faults high increase frames if low decrease Keep between bounds | Other COW Copy on Write fork optimization child shares parent pages read-only until write then copy saves memory fast fork Memory mapped files map file to memory address space file I/O via memory accesses sharing Kernel memory buddy system power of 2 splits merges buddies coalescing Slab allocator caches for kernel objects frequently allocated inode task_struct slabs pre-allocated efficient no fragmentation

Final Recap: 2 cooks same kitchen same salt jar Both need to add salt same time Cook A reads salt level Cook B also reads same level both add salt one addition lost That's Race Condition when 2 processes access shared variable count++ simultaneously lost update because count++ is 3 steps read-modify-write not atomic count=10 P1 reads 10 P2 reads 10 P1 adds 1 writes 11 P2 adds 1 writes 11 final 11 should be 12 lost One update lost Because count++ 3 steps read count from memory to register increment register write back to memory Not atomic can be interleaved To avoid race need Critical Section section of code where shared variable accessed Only one process can be in critical section at a time Requirements Mutual Exclusion only one in CS at a time Progress if no process in CS decision which enters CS cannot be postponed indefinitely Bounded Waiting bound on number of times other processes allowed to enter after a process requests entry no starvation Structure do { entry section → critical section → exit section → remainder section } while(true) Solutions Peterson's Solution for 2 processes P0 P1 Software solution uses flag[2] and turn flag[i]=true indicates Pi wants to enter CS turn indicates whose turn to enter Algorithm P0 flag[0]=true turn=1 while(flag[1] && turn==1) busy wait entry CS flag[0]=false exit P1 similar flag[1]=true turn=0 while(flag[0] && turn==0) busy wait Satisfies all 3 mutual exclusion progress bounded waiting Disadvantage busy waiting wastes CPU cycles spinlock TestAndSet hardware instruction Atomic instruction boolean TestAndSet(boolean *target) { boolean rv=*target; *target=true; return rv; } Atomic means indivisible cannot be interrupted Solution shared boolean lock=false initially Pi while(TestAndSet(&lock)) busy wait CS lock=false exit Ensures mutual exclusion progress but bounded waiting not guaranteed may starve Hardware support needed CompareAndSwap Similar atomic CAS(int *value int expected int new_value) atomically compares *value with expected if equal sets to new_value returns old *value Used to implement locks Disadvantages busy waiting solutions waste CPU cycles spinlock when waiting process loops continuously checking condition Solution blocking using semaphores instead of busy waiting Semaphore integer variable S accessed via only two atomic operations wait() P() and signal() V() indivisible no race condition Invented by Dijkstra Purpose synchronize processes/threads to avoid race conditions P()=proberen Dutch to test V()=verhogen Dutch to increment classic OS terminology Binary semaphore = 0/1 mutex lock S is only 0 or 1 Used as a lock/mutex for mutual exclusion 1=unlocked/free 0=locked/held Initial value 1 Process enters CS does wait(S) if S=1 becomes 0 enters if S=0 blocked Exit does signal(S) S becomes 1 wakes waiting Counting semaphore = 0→N resource instances S can range 0...N N=number of available resources/instances Tracks count of available resources/instances e.g., 3 printers S=3 Initial S=N Each allocation wait() decrements S each release signal() increments wait() = P() down operation S=S-1 if S<0→block process & add to wait queue Process put to sleep until semaphore available blocked not busy waiting in blocking implementation Pseudo wait(S) { S--; if(S<0) { add process to queue; block(); } } atomic signal() = V() up operation S=S+1 if there are waiting processes→wake up one process remove from queue wakeup() Pseudo signal(S) { S++; if(S<=0) { remove process from queue; wakeup(P); } } atomic Note If S<0 number of waiting processes =|S| If S<=0 after increment there were waiting processes Classic Problems Solved by Semaphores 1 Producer-Consumer Bounded Buffer Bounded buffer finite capacity buffer size N Producers produce items consumers consume Producers wait if buffer FULL Consumers wait if EMPTY Uses 3 semaphores empty=N initially count of empty slots full=0 initially count of full slots mutex=1 binary semaphore for mutual exclusion on buffer Producer wait(empty) wait(mutex) produce item to buffer signal(mutex) signal(full) Consumer wait(full) wait(mutex) consume item from buffer signal(mutex) signal(empty) Order of wait matters to avoid deadlock wait(empty) before wait(mutex) else deadlock possible 2 Readers-Writers Multiple readers can read simultaneously but writers require exclusive access no readers or writers while writing Readers priority→writers may suffer starvation if readers keep arriving writer waits long Solutions readers-preference writers-preference fair Uses mutex and wrt semaphore readcount variable 3 Dining Philosophers 5 philosophers 5 chopsticks arranged in circle each needs 2 chopsticks to eat left and right Potential deadlock if each holds left chopstick and waits for right circular wait Solutions allow only 4 philosophers to eat at a time counting semaphore 4 or odd philosopher picks left first even picks right first breaking circular wait or use monitor Implementation Busy waiting spinlock busy loop while S≤0 checks repeatedly wastes CPU cycles but no context switch overhead good for short waits multiprocessor Blocking process sleeps added to queue woken by signal()→efficient no CPU waste while waiting needs context switch Semaphores can be used for both mutual exclusion binary and resource counting counting. Segmentation User view program as logical segments not just pages Program naturally divided into segments Code holds instructions Data variables/globals Heap dynamic allocations Stack function calls/locals each has different purpose and size Unlike paging which is fixed size and no logical meaning segmentation matches programmer's view Example Code base=1000 limit=400 Data base=5000 limit=200 Heap base=6000 limit=500 Stack base=9000 limit=300 Segment Table Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 per process segment table Segmentation Translation Logical address=+ Physical address=base+offset if offset physical memory reduce multiprogramming suspend a process Ensures each process has enough frames to keep its working set Page Fault Frequency PFF Control thrashing based on page fault rate If page fault rate of a process high→need more frames allocate more frames If fault rate low→too many frames may reduce frames Keep fault rate between lower and upper bounds Other Concepts Copy on Write COW Fork optimization child process shares parent pages initially read-only until write occurs then copy on write creates copy only when written saves memory fast fork Example fork() child shares parent's pages marked COW when child or parent writes trap copy page then write Memory Mapped Files Map file to memory address space file I/O via memory accesses instead of read/write system calls convenient sharing Kernel Memory Allocation Buddy system allocates blocks of size power of 2 splits and merges buddies coalescing Slab allocator caches for kernel objects frequently allocated objects like inode task_struct slabs pre-allocated efficient no fragmentation Demand paging with copy on write and memory mapped files are modern VM techniques. If you remember Race Condition 2 processes access shared count++ simultaneously lost update count=10 P1 reads 10 P2 reads 10 P1 writes 11 P2 writes 11 final 11 should be 12 count++ read-modify-write 3 steps not atomic and Critical Section entry CS exit remainder 3 Requirements Mutual Exclusion only one in CS Progress if no process in CS decision cannot be postponed Bounded Waiting bound after request no starvation and Peterson's for 2 flag turn flag[i]=true interest turn whose turn busy waiting satisfies all 3 TestAndSet atomic returns old sets to 1 while(TestAndSet(&lock)) busy wait CS lock=false CompareAndSwap atomic CAS and Semaphore integer variable S accessed via wait() P() and signal() V() atomic indivisible no race Purpose synchronize processes/threads avoid race Dijkstra P=proberen V=verhogen and Binary 0/1 mutex lock S only 0 or 1 Used as lock/mutex 1=unlocked/free 0=locked/held Initial 1 and Counting 0→N resource instances S range 0...N N=number available Tracks count e.g., 3 printers S=3 Initial N and wait() P() down S=S-1 if S<0→block & add to wait queue put to sleep and signal() V() up S=S+1 if waiting→wake up one remove queue and Classic 1 Producer-Consumer bounded buffer finite N Producers wait if FULL Consumers wait if EMPTY Uses empty=N full=0 mutex=1 Producer wait(empty) wait(mutex) produce signal(mutex) signal(full) Consumer wait(full) wait(mutex) consume signal(mutex) signal(empty) Order wait(empty) before wait(mutex) avoid deadlock 2 Readers-Writers Multiple readers can read simultaneously Writers exclusive Readers priority→writers starvation readers-preference writers-preference fair mutex wrt readcount 3 Dining Philosophers 5 philosophers 5 chopsticks Each needs 2→deadlock Solutions allow only 4 counting semaphore 4 odd left first even right first break circular wait monitor and Implementation Busy waiting spinlock busy loop while S≤0 wastes CPU no context switch good short waits multiprocessor Blocking sleeps added to queue woken by signal efficient no waste needs context switch and Segmentation User view program as segments Code base=1000 limit=400 Data base=5000 limit=200 Heap base=6000 limit=500 Stack base=9000 limit=300 Each different purpose size and Segment Table Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 per process and Translation Logical=+ Physical=base+offset if offset physical reduce multiprogramming suspend Ensures each enough frames PFF Page Fault Frequency if faults high increase frames if low decrease Keep between bounds and Other COW Copy on Write fork optimization child shares parent pages read-only until write then copy saves memory fast fork Memory mapped files map file to memory address space file I/O via memory accesses sharing Kernel memory buddy system power of 2 splits merges buddies coalescing Slab allocator caches for kernel objects frequently allocated inode task_struct slabs pre-allocated efficient no fragmentation DSSSB 8 marks fixed!

Topper Revision 1 Page = Full Chapter

Process Synchronization

Race Condition 2 processes access shared count++ simultaneously lost update count=10 P1 reads 10 P2 reads 10 P1 writes 11 P2 writes 11 final 11 should be 12 count++ read-modify-write 3 steps not atomic | Critical Section entry CS exit remainder 3 Requirements Mutual Exclusion only one in CS Progress if no process in CS decision cannot be postponed Bounded Waiting bound after request no starvation | Peterson's for 2 flag turn flag[i]=true interest turn whose turn busy waiting satisfies all 3 TestAndSet atomic returns old sets to 1 while(TestAndSet(&lock)) busy wait CS lock=false CompareAndSwap atomic CAS

Semaphores

TypeValueUseInitial
Binary0/1 mutex lock S only 0 or 1Lock/mutex mutual exclusion 1=unlocked/free 0=locked/held1
Counting0→N resource instances S range 0...N N=number availableTracks count e.g., 3 printers S=3N
OperationPseudoAction
wait() P() downS=S-1 if S<0→block & add to wait queuePut to sleep until available
signal() V() upS=S+1 if waiting→wake up one remove queueWake up one process
  • Definition integer variable S accessed via wait() P() and signal() V() atomic indivisible no race Purpose synchronize to avoid race Dijkstra P=proberen to test V=verhogen to increment
  • If S<0 number waiting =|S| If S<=0 after increment there were waiting
  • Classic 1 Producer-Consumer bounded buffer finite N Producers wait if FULL Consumers wait if EMPTY Uses empty=N full=0 mutex=1 Producer wait(empty) wait(mutex) produce signal(mutex) signal(full) Consumer wait(full) wait(mutex) consume signal(mutex) signal(empty) Order wait(empty) before wait(mutex) avoid deadlock
  • 2 Readers-Writers Multiple readers can read simultaneously Writers exclusive no readers or writers while writing Readers priority→writers may suffer starvation if readers keep arriving writer waits long Solutions readers-preference writers-preference fair Uses mutex and wrt semaphore readcount variable
  • 3 Dining Philosophers 5 philosophers 5 chopsticks circle each needs 2 to eat left and right Potential deadlock if each holds left waits for right circular wait Solutions allow only 4 to eat at a time counting semaphore 4 or odd left first even right first breaking circular wait or use monitor
  • Implementation Busy waiting spinlock busy loop while S≤0 wastes CPU but no context switch good short waits multiprocessor Blocking process sleeps added to queue woken by signal→efficient no CPU waste needs context switch

Segmentation

SegmentBaseLimitPurpose
Code1000400holds instructions
Data5000200variables/globals
Heap6000500dynamic allocations
Stack9000300function calls/locals
  • Segment Table Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 per process
  • Translation Logical=+ Physical=base+offset if offset
  • Advantages Logical view natural code/data/stack/heap matches programming structure Protection each own base/limit perms read/write/execute e.g., code read-only execute Data read-write Sharing shared between processes e.g., shared library Variable size grow/shrink heap stack grow
  • Paging vs Segmentation Paging Fixed size pages 4KB No logical just page# Internal fragmentation small vs Segmentation Variable size Logical matches program structure External fragmentation holes need compaction
  • Segmented Paging Combined Segment divided into pages Logical=segment+page+offset Segment table→page table→frames Benefits logical segments + paging Reduces external frag vs pure segmentation allows shared/logical view Intel x86 segmentation+paging Disadvantage two-level translation overhead TLB helps

Virtual Memory

ConceptSteps/FormulaDetails
Virtual MemoryExecution not completely in memory only needed pages demand pagingAllows large programs larger than physical degree increases less I/O faster creation shared memory
Demand PagingOnly bring when needed page fault Steps 1 Trap page fault 2 Find free frame or victim replacement 3 Swap in from disk to frame if victim dirty write back 4 Update page table valid frame 5 Restart Valid bit indicates if in memory valid or on disk invalid but legalPage fault rate p Effective Access Time EAT=(1-p)*memory_access + p*page_fault_time memory ~100ns fault ~10ms p must be very low Example p=0.001 EAT=0.999*100+0.001*10,000,000=10,099.9ns high
ThrashingCPU utilization vs degree multiprogramming rises then falls Too many faults CPU swapping more than executing degree too high working set exceeds Effects low CPU high pagingControl Working Set keep working set in memory set of pages used in last Δ window Δ working set If sum working sets > physical reduce multiprogramming suspend Ensures each enough frames PFF Page Fault Frequency if faults high increase frames if low decrease Keep between bounds
OtherCOW Copy on Write fork optimization child shares parent pages read-only until write then copy saves memory fast fork Memory mapped files map file to memory address space file I/O via memory accesses sharing Kernel memory buddy system power of 2 splits merges buddies coalescing Slab allocator caches for kernel objects frequently allocated inode task_struct slabs pre-allocated efficient no fragmentationModern VM techniques

PYQ Traps:
• Race Condition 2 processes access shared count++ simultaneously lost update count=10 P1 reads 10 P2 reads 10 P1 writes 11 P2 writes 11 final 11 should be 12 count++ read-modify-write 3 steps not atomic
• Critical Section entry CS exit remainder 3 Requirements Mutual Exclusion only one in CS Progress if no process in CS decision cannot be postponed Bounded Waiting bound after request no starvation
• Peterson's for 2 flag turn flag[i]=true interest turn whose turn busy waiting satisfies all 3 TestAndSet atomic returns old sets to 1 while(TestAndSet(&lock)) busy wait CS lock=false CompareAndSwap atomic CAS
• Semaphore integer variable S accessed via wait() P() and signal() V() atomic indivisible no race Purpose synchronize to avoid race Dijkstra P=proberen V=verhogen
• Binary 0/1 mutex lock S only 0 or 1 Used as lock/mutex 1=unlocked/free 0=locked/held Initial 1
• Counting 0→N resource instances S range 0...N N=number available Tracks count e.g., 3 printers S=3 Initial N
• wait() P() down S=S-1 if S<0→block & add to wait queue put to sleep
• signal() V() up S=S+1 if waiting→wake up one remove queue
• Producer-Consumer bounded buffer finite N Producers wait if FULL Consumers wait if EMPTY Uses empty=N full=0 mutex=1 Producer wait(empty) wait(mutex) produce signal(mutex) signal(full) Consumer wait(full) wait(mutex) consume signal(mutex) signal(empty) Order wait(empty) before wait(mutex) avoid deadlock
• Readers-Writers Multiple readers can read simultaneously Writers exclusive Readers priority→writers starvation readers-preference writers-preference fair mutex wrt readcount
• Dining Philosophers 5 philosophers 5 chopsticks Each needs 2→deadlock Solutions allow only 4 counting semaphore 4 odd left first even right first break circular wait monitor
• Implementation Busy waiting spinlock busy loop while S≤0 wastes CPU no context switch good short waits multiprocessor Blocking sleeps added to queue woken by signal efficient no waste needs context switch
• Segmentation User view program as segments Code base=1000 limit=400 Data base=5000 limit=200 Heap base=6000 limit=500 Stack base=9000 limit=300 Each different purpose size
• Segment Table Seg# Base Limit 0→1000 400 1→5000 200 2→6000 500 3→9000 300 per process
• Translation Logical=+ Physical=base+offset if offset • Advantages Logical view natural code/data/stack/heap Protection each own base/limit perms read/write/execute Sharing shared between processes e.g., shared library Variable size grow/shrink heap stack grow
• Paging vs Segmentation Paging Fixed size pages 4KB No logical just page# Internal fragmentation small vs Segmentation Variable size Logical matches program structure External fragmentation holes need compaction
• Segmented Paging Combined Segment divided into pages Logical=segment+page+offset Segment table→page table→frames Benefits logical segments + paging Reduces external frag vs pure segmentation allows shared/logical view Intel x86 segmentation+paging Disadvantage two-level translation overhead TLB helps
• Virtual Memory execution not completely in memory only needed pages demand paging Allows large programs larger than physical degree increases less I/O faster creation shared memory
• Demand Paging only bring when needed page fault Steps 1 Trap page fault 2 Find free frame or victim replacement 3 Swap in from disk to frame if victim dirty write back 4 Update page table valid frame 5 Restart Valid bit indicates if in memory valid or on disk invalid but legal Page fault rate p Effective Access Time EAT=(1-p)*memory_access + p*page_fault_time memory ~100ns fault ~10ms p must be very low Example p=0.001 EAT=0.999*100+0.001*10,000,000=10,099.9ns high
• Thrashing CPU utilization vs degree multiprogramming rises then falls Too many faults CPU swapping more than executing degree too high working set exceeds Effects low CPU high paging
• Control Working Set keep working set in memory set of pages used in last Δ window Δ working set If sum working sets > physical reduce multiprogramming suspend Ensures each enough frames PFF Page Fault Frequency if faults high increase frames if low decrease Keep between bounds
• Other COW Copy on Write fork optimization child shares parent pages read-only until write then copy saves memory fast fork Memory mapped files map file to memory address space file I/O via memory accesses sharing Kernel memory buddy system power of 2 splits merges buddies coalescing Slab allocator caches for kernel objects frequently allocated inode task_struct slabs pre-allocated efficient no fragmentation

© 2026 pdcampus.in · All rights reserved. · Made with ❤️ for Indian students.