Title: Classical Synchronization Problems
1Classical Synchronization Problems
CS 345
Discussion 09 Chapter 4b
1
2Readers and Writers Problem
Readers/Writers
- Data object is shared (file, memory, registers)
- many processes that only read data (readers)
- many processes that only write data (writers)
- Conditions needing to be satisfied
- many can read at the same time (patron of
library) - only one writer at a time (librarian)
- no one allowed to read while someone is writing
- Different from producer/consumer (general case
with mutual exclusion of critical section)
possible for more efficient solution if only
writers write and readers read. - Solutions result in reader or writer priority
3Readers/Writers (priority?)
Readers/Writers
Semaphore rmutex1, wmutex 1 integer readcount
0
Only one writer at a time
The first reader makes sure no one can write
while(true) wait(wmutex) ltwrite to the
data objectgt signal(wmutex)
while(true) wait(rmutex) readcount
if (readcount 1) wait(wmutex)
signal(rmutex) ltread the datagt
wait(rmutex) readcount-- if (readcount
0) signal(wmutex) signal(rmutex)
Readers have priority! (subject to starvation)
Last one out allows writing again
More than one reader at a time
4Writers/Readers (priority?)
Readers/Writers
Semaphore outerQ, rsem, rmutex, wmutex, wsem 1
while(true) wait(outerQ) wait(rsem)
wait(rmutex) readcnt if
(readcnt 1) wait(wsem)
signal(rmutex) signal(rsem)
signal(outerQ) READ wait(rmutex)
readcnt-- if(readcnt 0)
signal(wsem) signal(rmutex)
while(true) wait(wmutex) writecnt
if (writecnt 1) wait(rsem)
signal(wmutex) wait(wsem) WRITE
signal(wsem) wait(wmutex) writecnt--
if (writecnt 0) signal(rsem)
signal(wmutex)
Additional readers queue here allowing writers to
jump ahead of the readers
Disable writers
Wait here until all readers done
Once a writer wants to write no new readers
allowed
Last reader out allows writers
Last writer out allows readers
5Barbershop Problem
Barbershop
- 3 barbers, each with a barber chair
- Haircuts vary in time
- Sofa can hold 4 customers
- Maximum of 20 in shop
- Customers wait outside if necessary
- When a chair is empty
- Customer sitting longest on sofa is served
- Customer standing the longest sits down
- After haircut, customer pays cashier at cash
register - Algorithm has a separate cashier, but often
barbers also take payment
6Fair Barbershop
Barbershop
procedure customer procedure
barber procedure cashier var custnr integer
var b_cust integer begin begin
begin repeat wait ( max_capacity )
repeat
wait( payment )
/ enter_shop /
wait( cust_ready )
wait( coord ) wait( mutex1 )
wait( mutex2 ) / accept
payment / count count 1
dequeue1( b_cust )
signal( coord ) custnr count
signal( mutex2 )
signal( receipt ) signal(
mutex1 ) wait( coord )
forever wait( sofa )
/ cut hair / end / sit
on sofa /
signal( coord ) wait( barber_chair )
signal( finishedb_cust ) / get
up from sofa / wait(
leave_b_chair ) signal( sofa )
signal( barber_chair ) / sit in barber
chair / forever wait( mutex2 )
end enqueue1( custnr ) signal(
cust_ready ) signal( mutex2 ) wait(
finishedcustnr ) / leave barber chair /
signal( leave_b_chair ) / pay /
signal( payment ) wait( receipt ) /
exit shop / signal( max_capacity ) end
program barbershop2 var max_capacity semaphore
(20) sofa semaphore (4) barber_chair,
coord semaphore (3) mutex1, mutex2
semaphore (1) cust_ready, leave_b_chair,
payment, receipt semaphore (0) finished
array 1..50 of semaphore (0) count integer
7The Dining Philosophers Problem
Dining Philosophers
- 5 philosophers who only eat and think.
- Each need to use 2 forks for eating.
- There are only 5 forks.
- Classical synchronization problem.
- Illustrates the difficulty of allocating
resources among process without deadlock and
starvation.
8Solution??
Dining Philosophers
Process Pi repeat think wait(forksi)
wait(forks(i1)5) eat signal(forks(i1)
5) signal(forksi) forever
- Each philosopher is a process.
- One semaphore per fork
- forks array0..4 of semaphores
- Initialization forksi.count1 for i0..4
- Deadlock if each philosopher starts by picking
left fork!
9Another Solution
Dining Philosophers
- A solution admit only 4 philosophers at a time
that tries to eat - Then 1 philosopher can always eat when the other
3 are holding 1 fork - Introduce semaphore T that limits to 4 the number
of philosophers sitting at the table - Initialize T.count4
Process Pi repeat think wait(T)
wait(forksi) wait(forks(i1)5) eat
signal(forks(i1)5) signal(forksi)
signal(T) forever
10Solving Dining Philosophers
Dining Philosophers
- Buy more Forks
- Equivalent to increasing resources
- Put fork down if 2nd fork busy
- Can produce livelock if philosophers stay
synchronized - Room Attendant
- Only let 4 of the philosophers into the room at
once - May have 4 philosophers in room, but only 1 can
eat - Left-Handed Philosophers (asymmetric solution)
- Grab forks in the other order (right fork, then
left fork) - Any mix will avoid deadlock (linear ordering on
forks) - A philosopher may only pick up forks in pairs.
- must allocate all resources at once
11Dining Philosophers
Monitor for Dining Philosophers
type dining-philosophers monitor var state
array0..4 of (thinking, hungry, eating) var
self array0..4 of condition procedure
entry pickup(i0..4) statei hungry
test(i) if (statei ! eating)
selfi.wait end procedure entry
putdown(i0..4) statei thinking
test((i 4) mod 5) test((i 1) mod 5)
end
procedure test(k0..4) if (state(k4) mod 5
! eating statek hungry
state(k1) mode 5 ! eating) statek
eating selfk.signal endif end begin
for i 0 to 4 statei thinking end
- Mutual exclusion?
- Only one process active inside the monitor
- Deadlocks?
- Possible Wont solve all problems
- Starvation?
- Yes, it is possible to starve a philosopher
12Processes and Threads
13Symmetric Multiprocessing
- Kernel can execute on any processor
- Typically each processor does self-scheduling
from the pool of available process or threads - Timer interrupt
- Ready queue
- SMP Support
- Any thread (including kernel threads) can run on
any processor - Soft affinity Try to reschedule a thread on the
same processor - Hard affinity Restrict a thread to certain
processors
14Symmetric Multiprocessor Organization
15SMP Organization
- Generally each processor has its own cache, share
memory and I/O - Design issues
- Simultaneous concurrent processes or threads
- Kernel routines must be reentrant to allow
multiple treads to execute them - Scheduling (Chap 10)
- Must avoid conflicts
- May be able to run threads concurrently
- Synchronization (Chap 5)
- Mutual exclusion, event ordering
- Memory management (Chap 7, 8)
- Deal with multiport memory
- Have a unified paging scheme
- Reliability and fault tolerance
- Solutions similar to normal case
16Microkernels
- Popularized by use in Mach O.S.
- Monolithic O.S.
- Built as a single large program, any routine can
call any other routine - Used in most early systems
- Layered O.S.
- Based on modular programming
- Major changes still had wide-spread effects on
other layers - Microkernel
- Only essential functions in the kernel
- File System, Device drivers, etc., are now
external subsystems/processes - Processes interact through messages passed
through the kernel
17Microkernel
- Identify and isolate a small operating system
core that contains only essential OS functions - Move many services included in the traditional
kernel OS to external subsystems - device drivers
- file systems
- virtual memory manager
- windowing system and security services
18Microkernel Design
- Primitive Memory Management
- Kernel handles virtualphysical mapping, rest is
a user mode process - V.M. module can decide what pages to move to/from
disk - Module can allocate memory
- Three microkernel memory operations
- Grant Grant pages to someone else (Grantor
gives up access to pages) - Map Map pages in another space (Both processes
can access page) - Flush Reclaim pages granted or mapped
- Interprocess Communication
- Based on messages
- I/O and Interrupts
- Handle interrupts as messages
19Microkernel OS
User Mode
Kernel Mode
20Microkernel Benefits
- Uniform Interface
- Same message for user/system services
- Extensibility
- Easy to add new services
- Modifications need only change directly affected
components - Could have multiple file services
- Flexibility
- Can customize system by omitting services
- Portability
- Isolate nearly all processor-specific code in the
kernel - Changes tend to be in logical areas
21Microkernel Benefits (continued)
- Reliability
- Easy to rigorously test kernel
- Fewer system calls to master
- Less interaction with other components
- Distributed System Support
- Just as easy to send a message to another machine
as this machine - Need system-wide unique Ids
- Processes dont have to know where a service
resides - Object-Orientated O.S.
- Lends discipline to the kernel
- Some systems (NT) incorporate OO principles into
the design
22Kernel Performance
- Sending a message generally slower than simple
kernel call - Depends on size of the microkernel
- First generation systems slower
- Then tried to include critical system items into
kernel (Mach) - Fewer user/system mode switches
- Lose some microkernel benefits
- Trying approach of very small kernel
- L4 - 12K code, 7 system calls
- Speed seems to match Unix
23Win 2000 Threads
- Thread States
- Ready Able to run
- Standby Scheduled to run
- Running
- Waiting Blocked or suspended
- Transition Not blocked, but cant run (paged
out of memory) - Terminated
- Support for O.S. Subsystem
- Process creation
- Begins with request from application
- Goes to protected subsystem
- Passed to executive, returns handle
- Win32, OS/2 use handle to create thread
- Return process/thread information
- Win2000 - client requests a new thread
- Thread inherits limits, etc. from parent
24Solaris Threads
- Four thread-related concepts
- Process Normal Unix process
- User-level Thread Thread library
- Lightweight Process Mapping between ULTs and
Kernel Threads - Kernel Thread Fundamental kernel scheduling
object - Also used for system functions
25Linux Threads
- Task structure maintained for each process/thread
- State (executing, ready, zombie, etc.)
- Scheduling information
- Process, user, group identifiers
- Interprocess communication info
- Links to parent, siblings, children
- Timers (time used, interval timer)
- File system Pointers to open files
- Virtual memory
- Processor-specific context
- Threads are implemented as processes that share
files, virtual memory, signals, etc. - Clone system call to create a thread
- ltpthread.hgt library provides more user-friendly
thread support