Lec06 Synchronization
Lec06 Synchronization
Synchronization
February 6, 2006
Prof. Anthony D. Joseph
http://inst.eecs.berkeley.edu/~cs162
Review: ThreadFork(): Create a New Thread
• ThreadFork() is a user-level procedure that
creates a new thread and places it on ready queue
• Arguments to ThreadFork()
– Pointer to application routine (fcnPtr)
– Pointer to array of arguments (fcnArgPtr)
– Size of stack to allocate
• Implementation
– Sanity Check arguments
– Enter Kernel-mode and Sanity Check arguments again
– Allocate new Stack and TCB
– Initialize TCB and place on ready list (Runnable).
ThreadRoot
Stack growth A
B(while)
yield
Stack growth
ThreadRoot
• Multithreaded version:
serverLoop() {
connection = AcceptCon();
ThreadFork(ServiceWebPage(),connection);
}
• Advantages of threaded version:
– Can share file caches kept in memory, results of CGI
scripts, other things
– Threads are much cheaper to create than processes, so
this has a lower per-request overhead
• What if too many requests come in at once?
2/6/06 Joseph CS162 ©UCB Spring 2006 Lec 6.6
Thread Pools
• Problem with previous version: Unbounded Threads
– When web-site becomes too popular – throughput sinks
• Instead, allocate a bounded “pool” of threads,
representing the maximum level of multiprogramming
Master
queue
Thread
Thread Pool
master() { slave(queue) {
allocThreads(slave,queue); while(TRUE) {
while(TRUE) { con=Dequeue(queue);
con=AcceptCon(); if (con==null)
Enqueue(queue,con); sleepOn(queue);
wakeUp(queue); else
} ServiceWebPage(con);
} }
2/6/06 Joseph CS162 ©UCB}Spring 2006 Lec 6.7
ATM Bank Server
A B C
Multiprogramming A B C A B C B
• Hand Simulation:
– And we’re off. A gets off to an early start
– B says “hmph, better go fast” and tries really hard
– A goes ahead and writes “1”
– B goes and writes “-1”
– A says “HUH??? I could have sworn I put a 1 there”
• Could this happen on a uniprocessor?
– Yes! Unlikely, but if you depending on it not happening,
it will and your system will break…
2/6/06 Joseph CS162 ©UCB Spring 2006 Lec 6.20
Motivation: “Too much milk”
• Great thing about OS’s – analogy between
problems in OS and problems in real life
– Help you understand real life problems better
– But, computers are much stupider than people
• Example: People need to coordinate:
Time Person A Person B
3:00 Look in Fridge. Out of milk
3:05 Leave for store
3:10 Arrive at store Look in Fridge. Out of milk
3:15 Buy milk Leave for store
3:20 Arrive home, put milk away Arrive at store
3:25 Buy milk
3:30 Arrive home, put milk away
#$@%
@ #$@
leave Note;
if (noMilk) {
if (noNote) {
leave Note;
buy milk;
}
}
remove note;
Higher-
level Locks Semaphores Monitors Send/Receive
API