Unit 2 · Operating Systems
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=
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.
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.
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.
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 =
- 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.
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.
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=
Process Synchronization
Semaphores
| Type | Value | Use | Initial |
|---|---|---|---|
| Binary | 0/1 mutex lock S only 0 or 1 | Lock/mutex mutual exclusion 1=unlocked/free 0=locked/held | 1 |
| Counting | 0→N resource instances S range 0...N N=number available | Tracks count e.g., 3 printers S=3 | N |
| Operation | Pseudo | Action |
|---|---|---|
| wait() P() down | S=S-1 if S<0→block & add to wait queue | Put to sleep until available |
| signal() V() up | S=S+1 if waiting→wake up one remove queue | Wake up one process |
Segmentation
| Segment | Base | Limit | Purpose |
|---|---|---|---|
| Code | 1000 | 400 | holds instructions |
| Data | 5000 | 200 | variables/globals |
| Heap | 6000 | 500 | dynamic allocations |
| Stack | 9000 | 300 | function calls/locals |
Virtual Memory
| Concept | Steps/Formula | Details |
|---|---|---|
| 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 | Modern 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=
• 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