Download presentation
Presentation is loading. Please wait.
Published byDustin Charles Modified over 9 years ago
1
© 2004, D. J. Foreman 1 Basic Synchronization
2
© 2004, D. J. Foreman 2 The Problem Given: "i" is global i++; expands into: LDAi ADAi,1 STAi What if interrupt occurs DURING 1 or 2? This is a “Critical Section” Incorrect values of "i" can result How do we prevent such errors
3
© 2004, D. J. Foreman 3 Solution Proposals 1. Turn interrupts off (not MP safe) 2. Flag in kernel to disallow context switch (works for kernel routines too) (MP safe) 3. Semaphores (MP safe) ■ Implemented as h/w inst ■ 80x86 has XCHG (not MP safe) Swaps RAM & register in 1 inst cycle not 1 bus cycle 4. Busy wait or "spin lock"
4
© 2004, D. J. Foreman 4 Clever S/W-Only Solution Shared memory int flag [0..1]; int turn Process 0 code flag[0] := T; turn := 1; while (flag [1] and turn =1) do no-op; critical section flag[0] := F;
5
© 2004, D. J. Foreman 5 Semaphores Sometimes called an “indivisible test and set.” In 80x86 - XCHG, swaps 1 RAM location and a register in one instruction cycle (but not one bus cycle – so not useful in multi-processor environments – unless enhanced.) Flag – global – initially 0 WAITMOVAX,1 XCHGFLAG,AX CMPAX,1 JEWAIT ---- critical section MOVFLAG,0
6
© 2004, D. J. Foreman 6 Spin Locks While (flag); // loops until flag=0 Wastes CPU time Makes user seem “bad”
7
© 2004, D. J. Foreman 7 Another Critical Section Problem Loadr1,bal Loadr2,amount Addr1,r2 Storer1,bal Loadr1,bal Loadr2,amount Subr1,r2 Storer1,bal p1, p2 are in a race bal=bal + amount bal=bal - amount interrupt context-switch
8
© 2004, D. J. Foreman 8 Locking a Critical Section While(lock) wait; lock=true Loadr1,bal Loadr2,amount Addr1,r2 Storer1,bal lock=false While(lock) wait; lock=true; Loadr1,bal Loadr2,amount Subr1,r2 Storer1,bal lock=false bal=bal + amountbal=bal - amount
9
© 2004, D. J. Foreman 9 Wait & Signal Classical definitions ■ Wait – Originally was P(s) DO WHILE (s<=0) wait;// The wait is interruptible s=s-1; ■ Signal - Originally was V(s) s=s+1; Remember: these must appear as ATOMIC operations to the application "s" is global
10
© 2004, D. J. Foreman 10 Strategies 1. User-only mode software 2. Disabling interrupts 3. H/W & O/S support
11
© 2004, D. J. Foreman 11 Acceptable Solutions 1. One process at a time in CritSec 2. Entry decision made by entrants 3. No indefinite wait allowed 4. Limit to predecessors
12
© 2004, D. J. Foreman 12 Additional Problems Semaphores only protect the CritSec Signaling adds need for more semaphores Classical problems: ■ Bounded Buffer also known as Producer-Consumer ■ Readers & Writers Readers have precedence Writers have precedence
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.