SlideShare a Scribd company logo
Full Solution to Bounded Buffer
Semaphore fullBuffer = 0; // Initially, no coke
Semaphore emptyBuffers = numBuffers;
// Initially, num empty slots
Semaphore mutex = 1; // No one using machine
Producer(item) {
emptyBuffers.P(); // Wait until space
mutex.P(); // Wait until buffer free
Enqueue(item);
mutex.V();
fullBuffers.V(); // Tell consumers there is
// more coke
}
Consumer() {
fullBuffers.P(); // Check if there’s a coke
mutex.P(); // Wait until machine free
item = Dequeue();
mutex.V();
emptyBuffers.V(); // tell producer need more
return item;
}
Discussion about Solution
• Why asymmetry?
• Producer does: emptyBuffer.P(), fullBuffer.V()
• Consumer does: fullBuffer.P(), emptyBuffer.V()
• Is order of P’s important?
• Yes! Can cause deadlock:
Producer(item) {
mutex.P(); // Wait until buffer free
emptyBuffers.P(); // Could wait forever!
Enqueue(item);
mutex.V();
fullBuffers.V(); // Tell consumers more coke
}
• Is order of V’s important?
• No, except that it might affect scheduling efficiency
• What if we have 2 producers or 2 consumers?
• Do we need to change anything?
Motivation for Monitors and Condition Variables
• Semaphores are a huge step up, but:
• They are confusing because they are dual purpose:
• Both mutual exclusion and scheduling constraints
• Example: the fact that flipping of P’s in bounded buffer gives deadlock is not immediately obvious
• Cleaner idea: Use locks for mutual exclusion and condition variables for scheduling
constraints
• Definition: Monitor: a lock and zero or more condition variables for
managing concurrent access to shared data
• Use of Monitors is a programming paradigm
• Some languages like Java provide monitors in the language
• The lock provides mutual exclusion to shared data:
• Always acquire before accessing shared data structure
• Always release after finishing with shared data
• Lock initially free
Simple Monitor Example (version 1)
• Here is an (infinite) synchronized queue
Lock lock;
Queue queue;
AddToQueue(item) {
lock.Acquire(); // Lock shared data
queue.enqueue(item); // Add item
lock.Release(); // Release Lock
}
RemoveFromQueue() {
lock.Acquire(); // Lock shared data
item = queue.dequeue();// Get next item or null
lock.Release(); // Release Lock
return(item); // Might return null
}
• Not very interesting use of “Monitor”
• It only uses a lock with no condition variables
• Cannot put consumer to sleep if no work!
Condition Variables
• How do we change the RemoveFromQueue() routine to wait until something
is on the queue?
• Could do this by keeping a count of the number of things on the queue (with
semaphores), but error prone
• Condition Variable: a queue of threads waiting for something inside a critical
section
• Key idea: allow sleeping inside critical section by atomically releasing lock at time we
go to sleep
• Contrast to semaphores: Can’t wait inside critical section
• Operations:
• Wait(&lock): Atomically release lock and go to sleep. Re-acquire lock later, before
returning.
• Signal(): Wake up one waiter, if any
• Broadcast(): Wake up all waiters
• Rule: Must hold lock when doing condition variable ops!
• In Birrell paper, he says can perform signal() outside of lock – IGNORE HIM (this is only
an optimization)
Complete Monitor Example (with condition variable)
• Here is an (infinite) synchronized queue
Lock lock;
Condition dataready;
Queue queue;
AddToQueue(item) {
lock.Acquire(); // Get Lock
queue.enqueue(item); // Add item
dataready.signal(); // Signal any waiters
lock.Release(); // Release Lock
}
RemoveFromQueue() {
lock.Acquire(); // Get Lock
while (queue.isEmpty()) {
dataready.wait(&lock); // If nothing, sleep
}
item = queue.dequeue(); // Get next item
lock.Release(); // Release Lock
return(item);
Mesa vs. Hoare monitors
• Need to be careful about precise definition of signal and wait. Consider a
piece of our dequeue code:
while (queue.isEmpty()) {
dataready.wait(&lock); // If nothing, sleep
}
item = queue.dequeue(); // Get next item
• Why didn’t we do this?
if (queue.isEmpty()) {
dataready.wait(&lock); // If nothing, sleep
}
item = queue.dequeue(); // Get next item
• Answer: depends on the type of scheduling
• Hoare-style (most textbooks):
• Signaler gives lock, CPU to waiter; waiter runs immediately
• Waiter gives up lock, processor back to signaler when it exits critical section or if it waits again
• Mesa-style (Nachos, most real operating systems):
• Signaler keeps lock and processor
• Waiter placed on ready queue with no special priority
• Practically, need to check condition again after wait
Using of Compare&Swap for queues
• compare&swap (&address, reg1, reg2) { /* 68000 */
if (reg1 == M[address]) {
M[address] = reg2;
return success;
} else {
return failure;
}
}
Here is an atomic add to linked-list function:
addToQueue(&object) {
do { // repeat until no conflict
ld r1, M[root] // Get ptr to current head
st r1, M[object] // Save link in new object
} until (compare&swap(&root,r1,object));
}
root next next
next
New
Object
Readers/Writers Problem
• Motivation: Consider a shared database
• Two classes of users:
• Readers – never modify database
• Writers – read and modify database
• Is using a single lock on the whole database sufficient?
• Like to have many readers at the same time
• Only one writer at a time
R
R
R
W
Basic Readers/Writers Solution
• Correctness Constraints:
• Readers can access database when no writers
• Writers can access database when no readers or writers
• Only one thread manipulates state variables at a time
• Basic structure of a solution:
• Reader()
Wait until no writers
Access data base
Check out – wake up a waiting writer
• Writer()
Wait until no active readers or writers
Access database
Check out – wake up waiting readers or writer
• State variables (Protected by a lock called “lock”):
• int AR: Number of active readers; initially = 0
• int WR: Number of waiting readers; initially = 0
• int AW: Number of active writers; initially = 0
• int WW: Number of waiting writers; initially = 0
• Condition okToRead = NIL
• Conditioin okToWrite = NIL
Code for a Reader
Reader() {
// First check self into system
lock.Acquire();
while ((AW + WW) > 0) { // Is it safe to read?
WR++; // No. Writers exist
okToRead.wait(&lock); // Sleep on cond var
WR--; // No longer waiting
}
AR++; // Now we are active!
lock.release();
// Perform actual read-only access
AccessDatabase(ReadOnly);
// Now, check out of system
lock.Acquire();
AR--; // No longer active
if (AR == 0 && WW > 0) // No other active readers
okToWrite.signal(); // Wake up one writer
lock.Release();
}
Code for a Writer
Writer() {
// First check self into system
lock.Acquire();
while ((AW + AR) > 0) { // Is it safe to write?
WW++; // No. Active users exist
okToWrite.wait(&lock); // Sleep on cond var
WW--; // No longer waiting
}
AW++; // Now we are active!
lock.release();
// Perform actual read/write access
AccessDatabase(ReadWrite);
// Now, check out of system
lock.Acquire();
AW--; // No longer active
if (WW > 0){ // Give priority to writers
okToWrite.signal(); // Wake up one writer
} else if (WR > 0) { // Otherwise, wake reader
okToRead.broadcast(); // Wake all readers
}
lock.Release();
}
Simulation of Readers/Writers solution
• Consider the following sequence of operators:
• R1, R2, W1, R3
• On entry, each reader checks the following:
while ((AW + WW) > 0) { // Is it safe to read?
WR++; // No. Writers exist
okToRead.wait(&lock); // Sleep on cond var
WR--; // No longer waiting
}
AR++; // Now we are active!
• First, R1 comes along:
AR = 1, WR = 0, AW = 0, WW = 0
• Next, R2 comes along:
AR = 2, WR = 0, AW = 0, WW = 0
• Now, readers make take a while to access database
• Situation: Locks released
• Only AR is non-zero
Simulation(2)
• Next, W1 comes along:
while ((AW + AR) > 0) { // Is it safe to write?
WW++; // No. Active users exist
okToWrite.wait(&lock); // Sleep on cond var
WW--; // No longer waiting
}
AW++;
• Can’t start because of readers, so go to sleep:
AR = 2, WR = 0, AW = 0, WW = 1
• Finally, R3 comes along:
AR = 2, WR = 1, AW = 0, WW = 1
• Now, say that R2 finishes before R1:
AR = 1, WR = 1, AW = 0, WW = 1
• Finally, last of first two readers (R1) finishes and wakes up writer:
if (AR == 0 && WW > 0) // No other active readers
okToWrite.signal(); // Wake up one writer
Simulation(3)
• When writer wakes up, get:
AR = 0, WR = 1, AW = 1, WW = 0
• Then, when writer finishes:
if (WW > 0){ // Give priority to writers
okToWrite.signal(); // Wake up one writer
} else if (WR > 0) { // Otherwise, wake reader
okToRead.broadcast(); // Wake all readers
}
• Writer wakes up reader, so get:
AR = 1, WR = 0, AW = 0, WW = 0
• When reader completes, we are finished
Questions
• Can readers starve? Consider Reader() entry code:
while ((AW + WW) > 0) { // Is it safe to read?
WR++; // No. Writers exist
okToRead.wait(&lock); // Sleep on cond var
WR--; // No longer waiting
}
AR++; // Now we are active!
• What if we erase the condition check in Reader exit?
AR--; // No longer active
if (AR == 0 && WW > 0) // No other active readers
okToWrite.signal(); // Wake up one writer
• Further, what if we turn the signal() into broadcast()
AR--; // No longer active
okToWrite.broadcast(); // Wake up one writer
• Finally, what if we use only one condition variable (call it “okToContinue”)
instead of two separate ones?
• Both readers and writers sleep on this variable
• Must use broadcast() instead of signal()
Can we construct Monitors from Semaphores?
• Locking aspect is easy: Just use a mutex
• Can we implement condition variables this way?
Wait() { semaphore.P(); }
Signal() { semaphore.V(); }
• Doesn’t work: Wait() may sleep with lock held
• Does this work better?
Wait(Lock lock) {
lock.Release();
semaphore.P();
lock.Acquire();
}
Signal() { semaphore.V(); }
• No: Condition vars have no history, semaphores have history:
• What if thread signals and no one is waiting? NO-OP
• What if thread later waits? Thread Waits
• What if thread V’s and noone is waiting? Increment
• What if thread later does P? Decrement and continue
Construction of Monitors from Semaphores
• Problem with previous try:
• P and V are commutative – result is the same no matter what order they occur
• Condition variables are NOT commutative
• Does this fix the problem?
Wait(Lock lock) {
lock.Release();
semaphore.P();
lock.Acquire();
}
Signal() {
if semaphore queue is not empty
semaphore.V();
}
• Not legal to look at contents of semaphore queue
• There is a race condition – signaler can slip in after lock release and before waiter
executes semaphore.P()
• It is actually possible to do this correctly
• Complex solution for Hoare scheduling in book
• Can you come up with simpler Mesa-scheduled solution?
Monitor Conclusion
• Monitors represent the logic of the program
• Wait if necessary
• Signal when change something so any waiting threads can proceed
• Basic structure of monitor-based program:
lock
while (need to wait) {
condvar.wait();
}
unlock
do something so no need to wait
lock
condvar.signal();
unlock
Check and/or update
state variables
Wait if necessary
Check and/or update
state variables
C-Language Support for Synchronization
• C language: Pretty straightforward synchronization
• Just make sure you know all the code paths out of a critical section
int Rtn() {
lock.acquire();
…
if (exception) {
lock.release();
return errReturnCode;
}
…
lock.release();
return OK;
}
• Watch out for setjmp/longjmp!
• Can cause a non-local jump out of procedure
• In example, procedure E calls longjmp, poping stack back to procedure B
• If Procedure C had lock.acquire, problem!
Proc A
Proc B
Calls setjmp
Proc C
lock.acquire
Proc D
Proc E
Calls longjmp
Stackgrowth
C++ Language Support for Synchronization
• Languages with exceptions like C++
• Languages that support exceptions are problematic (easy to make a non-local exit
without releasing lock)
• Consider:
void Rtn() {
lock.acquire();
…
DoFoo();
…
lock.release();
}
void DoFoo() {
…
if (exception) throw errException;
…
}
• Notice that an exception in DoFoo() will exit without releasing the lock
C++ Language Support for Synchronization
• Must catch all exceptions in critical sections
• Catch exceptions, release lock, and re-throw exception:
void Rtn() {
lock.acquire();
try {
…
DoFoo();
…
} catch (…) { // catch exception
lock.release(); // release lock
throw; // re-throw the exception
}
lock.release();
}
void DoFoo() {
…
if (exception) throw errException;
…
}
• Even Better: auto_ptr<T> facility. See C++ Spec.
• Can deallocate/free lock regardless of exit method
Java Language Support for Synchronization
• Java has explicit support for threads and thread synchronization
• Bank Account example:
class Account {
private int balance;
// object constructor
public Account (int initialBalance) {
balance = initialBalance;
}
public synchronized int getBalance() {
return balance;
}
public synchronized void deposit(int amount) {
balance += amount;
}
}
• Every object has an associated lock which gets automatically acquired and released
on entry and exit from a synchronized method.
Java Language Support for Synchronization
• Java also has synchronized statements:
synchronized (object) {
…
}
• Since every Java object has an associated lock, this type of statement acquires and
releases the object’s lock on entry and exit of the body
• Works properly even with exceptions:
synchronized (object) {
…
DoFoo();
…
}
void DoFoo() {
throw errException;
}
Java Language Support for Synchronization
• In addition to a lock, every object has a single condition variable associated
with it
• How to wait inside a synchronization method of block:
• void wait(long timeout); // Wait for timeout
• void wait(long timeout, int nanoseconds); //variant
• void wait();
• How to signal in a synchronized method or block:
• void notify(); // wakes up oldest waiter
• void notifyAll(); // like broadcast, wakes everyone
• Condition variables can wait for a bounded length of time. This is useful for handling
exception cases:
t1 = time.now();
while (!ATMRequest()) {
wait (CHECKPERIOD);
t2 = time.new();
if (t2 – t1 > LONG_TIME) checkMachine();
}
• Not all Java VMs equivalent!
• Different scheduling policies, not necessarily preemptive!

More Related Content

What's hot

CS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSCS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMS
Kathirvel Ayyaswamy
 
8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems
Dr Sandeep Kumar Poonia
 
Delay , Loss & Throughput
Delay , Loss & ThroughputDelay , Loss & Throughput
Delay , Loss & Throughput
Tutor in Tuition Classes
 
Imap(internet massege access protocaols)
Imap(internet massege access protocaols)Imap(internet massege access protocaols)
Imap(internet massege access protocaols)
shashikant pabari
 
Introduction to Distributed System
Introduction to Distributed SystemIntroduction to Distributed System
Introduction to Distributed System
Sunita Sahu
 
Ch4 memory management
Ch4 memory managementCh4 memory management
Ch4 memory management
Bullz Musetsho
 
Synchronization in distributed computing
Synchronization in distributed computingSynchronization in distributed computing
Synchronization in distributed computing
SVijaylakshmi
 
Distributed os
Distributed osDistributed os
Distributed os
sidra naz
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
chidabdu
 
Thread scheduling in Operating Systems
Thread scheduling in Operating SystemsThread scheduling in Operating Systems
Thread scheduling in Operating Systems
Nitish Gulati
 
Distributed shred memory architecture
Distributed shred memory architectureDistributed shred memory architecture
Distributed shred memory architecture
Maulik Togadiya
 
operating system question bank
operating system question bankoperating system question bank
operating system question bank
rajatdeep kaur
 
Clock synchronization in distributed system
Clock synchronization in distributed systemClock synchronization in distributed system
Clock synchronization in distributed system
Sunita Sahu
 
NFS(Network File System)
NFS(Network File System)NFS(Network File System)
NFS(Network File System)
udamale
 
RT linux
RT linuxRT linux
RT linux
SARITHA REDDY
 
Pipes in Windows and Linux.
Pipes in Windows and Linux.Pipes in Windows and Linux.
Pipes in Windows and Linux.
Junaid Lodhi
 
Telnet & SSH Configuration
Telnet & SSH ConfigurationTelnet & SSH Configuration
Telnet & SSH Configuration
Vinod Gour
 
Windows CE
Windows CEWindows CE
Windows CE
Mayank Garg
 
Arp (address resolution protocol)
Arp (address resolution protocol)Arp (address resolution protocol)
Arp (address resolution protocol)
tigerbt
 
Operating system services 9
Operating system services 9Operating system services 9
Operating system services 9
myrajendra
 

What's hot (20)

CS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMSCS9222 ADVANCED OPERATING SYSTEMS
CS9222 ADVANCED OPERATING SYSTEMS
 
8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems
 
Delay , Loss & Throughput
Delay , Loss & ThroughputDelay , Loss & Throughput
Delay , Loss & Throughput
 
Imap(internet massege access protocaols)
Imap(internet massege access protocaols)Imap(internet massege access protocaols)
Imap(internet massege access protocaols)
 
Introduction to Distributed System
Introduction to Distributed SystemIntroduction to Distributed System
Introduction to Distributed System
 
Ch4 memory management
Ch4 memory managementCh4 memory management
Ch4 memory management
 
Synchronization in distributed computing
Synchronization in distributed computingSynchronization in distributed computing
Synchronization in distributed computing
 
Distributed os
Distributed osDistributed os
Distributed os
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
 
Thread scheduling in Operating Systems
Thread scheduling in Operating SystemsThread scheduling in Operating Systems
Thread scheduling in Operating Systems
 
Distributed shred memory architecture
Distributed shred memory architectureDistributed shred memory architecture
Distributed shred memory architecture
 
operating system question bank
operating system question bankoperating system question bank
operating system question bank
 
Clock synchronization in distributed system
Clock synchronization in distributed systemClock synchronization in distributed system
Clock synchronization in distributed system
 
NFS(Network File System)
NFS(Network File System)NFS(Network File System)
NFS(Network File System)
 
RT linux
RT linuxRT linux
RT linux
 
Pipes in Windows and Linux.
Pipes in Windows and Linux.Pipes in Windows and Linux.
Pipes in Windows and Linux.
 
Telnet & SSH Configuration
Telnet & SSH ConfigurationTelnet & SSH Configuration
Telnet & SSH Configuration
 
Windows CE
Windows CEWindows CE
Windows CE
 
Arp (address resolution protocol)
Arp (address resolution protocol)Arp (address resolution protocol)
Arp (address resolution protocol)
 
Operating system services 9
Operating system services 9Operating system services 9
Operating system services 9
 

Similar to Full solution to bounded buffer

Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threads
Syed Zaid Irshad
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
Wayne Jones Jnr
 
Os3
Os3Os3
Operating systems
Operating systemsOperating systems
Operating systems
Jonathan Alvarado
 
Classic synchronization
Classic synchronizationClassic synchronization
Classic synchronization
hina firdaus
 
Operating systems
Operating systemsOperating systems
Operating systems
Eduardo Triana
 
Operating systems
Operating systemsOperating systems
Operating systems
Jonathan Alvarado
 
Operating systems
Operating systemsOperating systems
Operating systems
Jonathan Alvarado
 
Operating systems
Operating systemsOperating systems
Operating systems
Jonathan Alvarado
 
UNIT III Process Synchronization.docx
UNIT III Process Synchronization.docxUNIT III Process Synchronization.docx
UNIT III Process Synchronization.docx
karthikaparthasarath
 
Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Dead Lock Analysis of spin_lock() in Linux Kernel (english)Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Sneeker Yeh
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
priyank09
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
ssuserc70988
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
RuthikReddyGarlapati
 
Operating systems
Operating systemsOperating systems
Operating systems
Abraham
 
Operating systems
Operating systemsOperating systems
Operating systems
Abraham
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waiting
Roman Elizarov
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
Maxim Volgin
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
Saúl Ibarra Corretgé
 

Similar to Full solution to bounded buffer (20)

Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threads
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
 
Os3
Os3Os3
Os3
 
Operating systems
Operating systemsOperating systems
Operating systems
 
Classic synchronization
Classic synchronizationClassic synchronization
Classic synchronization
 
Operating systems
Operating systemsOperating systems
Operating systems
 
Operating systems
Operating systemsOperating systems
Operating systems
 
Operating systems
Operating systemsOperating systems
Operating systems
 
Operating systems
Operating systemsOperating systems
Operating systems
 
UNIT III Process Synchronization.docx
UNIT III Process Synchronization.docxUNIT III Process Synchronization.docx
UNIT III Process Synchronization.docx
 
Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Dead Lock Analysis of spin_lock() in Linux Kernel (english)Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Dead Lock Analysis of spin_lock() in Linux Kernel (english)
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
 
Operating systems
Operating systemsOperating systems
Operating systems
 
Operating systems
Operating systemsOperating systems
Operating systems
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waiting
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 

More from Syed Zaid Irshad

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
Syed Zaid Irshad
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
Syed Zaid Irshad
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
Syed Zaid Irshad
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
Syed Zaid Irshad
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
Syed Zaid Irshad
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
Syed Zaid Irshad
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
Syed Zaid Irshad
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
Syed Zaid Irshad
 
C Language
C LanguageC Language
C Language
Syed Zaid Irshad
 
Flowchart
FlowchartFlowchart
Flowchart
Syed Zaid Irshad
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
Syed Zaid Irshad
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
Syed Zaid Irshad
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
Syed Zaid Irshad
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
Syed Zaid Irshad
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
Syed Zaid Irshad
 
Data Communication
Data CommunicationData Communication
Data Communication
Syed Zaid Irshad
 
Information Networks
Information NetworksInformation Networks
Information Networks
Syed Zaid Irshad
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
Syed Zaid Irshad
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
Syed Zaid Irshad
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
Syed Zaid Irshad
 

More from Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
C Language
C LanguageC Language
C Language
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 

Recently uploaded

Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
architagupta876
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
People as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimalaPeople as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimala
riddhimaagrawal986
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
Madan Karki
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 

Recently uploaded (20)

Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
People as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimalaPeople as resource Grade IX.pdf minimala
People as resource Grade IX.pdf minimala
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 

Full solution to bounded buffer

  • 1. Full Solution to Bounded Buffer Semaphore fullBuffer = 0; // Initially, no coke Semaphore emptyBuffers = numBuffers; // Initially, num empty slots Semaphore mutex = 1; // No one using machine Producer(item) { emptyBuffers.P(); // Wait until space mutex.P(); // Wait until buffer free Enqueue(item); mutex.V(); fullBuffers.V(); // Tell consumers there is // more coke } Consumer() { fullBuffers.P(); // Check if there’s a coke mutex.P(); // Wait until machine free item = Dequeue(); mutex.V(); emptyBuffers.V(); // tell producer need more return item; }
  • 2. Discussion about Solution • Why asymmetry? • Producer does: emptyBuffer.P(), fullBuffer.V() • Consumer does: fullBuffer.P(), emptyBuffer.V() • Is order of P’s important? • Yes! Can cause deadlock: Producer(item) { mutex.P(); // Wait until buffer free emptyBuffers.P(); // Could wait forever! Enqueue(item); mutex.V(); fullBuffers.V(); // Tell consumers more coke } • Is order of V’s important? • No, except that it might affect scheduling efficiency • What if we have 2 producers or 2 consumers? • Do we need to change anything?
  • 3. Motivation for Monitors and Condition Variables • Semaphores are a huge step up, but: • They are confusing because they are dual purpose: • Both mutual exclusion and scheduling constraints • Example: the fact that flipping of P’s in bounded buffer gives deadlock is not immediately obvious • Cleaner idea: Use locks for mutual exclusion and condition variables for scheduling constraints • Definition: Monitor: a lock and zero or more condition variables for managing concurrent access to shared data • Use of Monitors is a programming paradigm • Some languages like Java provide monitors in the language • The lock provides mutual exclusion to shared data: • Always acquire before accessing shared data structure • Always release after finishing with shared data • Lock initially free
  • 4. Simple Monitor Example (version 1) • Here is an (infinite) synchronized queue Lock lock; Queue queue; AddToQueue(item) { lock.Acquire(); // Lock shared data queue.enqueue(item); // Add item lock.Release(); // Release Lock } RemoveFromQueue() { lock.Acquire(); // Lock shared data item = queue.dequeue();// Get next item or null lock.Release(); // Release Lock return(item); // Might return null } • Not very interesting use of “Monitor” • It only uses a lock with no condition variables • Cannot put consumer to sleep if no work!
  • 5. Condition Variables • How do we change the RemoveFromQueue() routine to wait until something is on the queue? • Could do this by keeping a count of the number of things on the queue (with semaphores), but error prone • Condition Variable: a queue of threads waiting for something inside a critical section • Key idea: allow sleeping inside critical section by atomically releasing lock at time we go to sleep • Contrast to semaphores: Can’t wait inside critical section • Operations: • Wait(&lock): Atomically release lock and go to sleep. Re-acquire lock later, before returning. • Signal(): Wake up one waiter, if any • Broadcast(): Wake up all waiters • Rule: Must hold lock when doing condition variable ops! • In Birrell paper, he says can perform signal() outside of lock – IGNORE HIM (this is only an optimization)
  • 6. Complete Monitor Example (with condition variable) • Here is an (infinite) synchronized queue Lock lock; Condition dataready; Queue queue; AddToQueue(item) { lock.Acquire(); // Get Lock queue.enqueue(item); // Add item dataready.signal(); // Signal any waiters lock.Release(); // Release Lock } RemoveFromQueue() { lock.Acquire(); // Get Lock while (queue.isEmpty()) { dataready.wait(&lock); // If nothing, sleep } item = queue.dequeue(); // Get next item lock.Release(); // Release Lock return(item);
  • 7. Mesa vs. Hoare monitors • Need to be careful about precise definition of signal and wait. Consider a piece of our dequeue code: while (queue.isEmpty()) { dataready.wait(&lock); // If nothing, sleep } item = queue.dequeue(); // Get next item • Why didn’t we do this? if (queue.isEmpty()) { dataready.wait(&lock); // If nothing, sleep } item = queue.dequeue(); // Get next item • Answer: depends on the type of scheduling • Hoare-style (most textbooks): • Signaler gives lock, CPU to waiter; waiter runs immediately • Waiter gives up lock, processor back to signaler when it exits critical section or if it waits again • Mesa-style (Nachos, most real operating systems): • Signaler keeps lock and processor • Waiter placed on ready queue with no special priority • Practically, need to check condition again after wait
  • 8. Using of Compare&Swap for queues • compare&swap (&address, reg1, reg2) { /* 68000 */ if (reg1 == M[address]) { M[address] = reg2; return success; } else { return failure; } } Here is an atomic add to linked-list function: addToQueue(&object) { do { // repeat until no conflict ld r1, M[root] // Get ptr to current head st r1, M[object] // Save link in new object } until (compare&swap(&root,r1,object)); } root next next next New Object
  • 9. Readers/Writers Problem • Motivation: Consider a shared database • Two classes of users: • Readers – never modify database • Writers – read and modify database • Is using a single lock on the whole database sufficient? • Like to have many readers at the same time • Only one writer at a time R R R W
  • 10. Basic Readers/Writers Solution • Correctness Constraints: • Readers can access database when no writers • Writers can access database when no readers or writers • Only one thread manipulates state variables at a time • Basic structure of a solution: • Reader() Wait until no writers Access data base Check out – wake up a waiting writer • Writer() Wait until no active readers or writers Access database Check out – wake up waiting readers or writer • State variables (Protected by a lock called “lock”): • int AR: Number of active readers; initially = 0 • int WR: Number of waiting readers; initially = 0 • int AW: Number of active writers; initially = 0 • int WW: Number of waiting writers; initially = 0 • Condition okToRead = NIL • Conditioin okToWrite = NIL
  • 11. Code for a Reader Reader() { // First check self into system lock.Acquire(); while ((AW + WW) > 0) { // Is it safe to read? WR++; // No. Writers exist okToRead.wait(&lock); // Sleep on cond var WR--; // No longer waiting } AR++; // Now we are active! lock.release(); // Perform actual read-only access AccessDatabase(ReadOnly); // Now, check out of system lock.Acquire(); AR--; // No longer active if (AR == 0 && WW > 0) // No other active readers okToWrite.signal(); // Wake up one writer lock.Release(); }
  • 12. Code for a Writer Writer() { // First check self into system lock.Acquire(); while ((AW + AR) > 0) { // Is it safe to write? WW++; // No. Active users exist okToWrite.wait(&lock); // Sleep on cond var WW--; // No longer waiting } AW++; // Now we are active! lock.release(); // Perform actual read/write access AccessDatabase(ReadWrite); // Now, check out of system lock.Acquire(); AW--; // No longer active if (WW > 0){ // Give priority to writers okToWrite.signal(); // Wake up one writer } else if (WR > 0) { // Otherwise, wake reader okToRead.broadcast(); // Wake all readers } lock.Release(); }
  • 13. Simulation of Readers/Writers solution • Consider the following sequence of operators: • R1, R2, W1, R3 • On entry, each reader checks the following: while ((AW + WW) > 0) { // Is it safe to read? WR++; // No. Writers exist okToRead.wait(&lock); // Sleep on cond var WR--; // No longer waiting } AR++; // Now we are active! • First, R1 comes along: AR = 1, WR = 0, AW = 0, WW = 0 • Next, R2 comes along: AR = 2, WR = 0, AW = 0, WW = 0 • Now, readers make take a while to access database • Situation: Locks released • Only AR is non-zero
  • 14. Simulation(2) • Next, W1 comes along: while ((AW + AR) > 0) { // Is it safe to write? WW++; // No. Active users exist okToWrite.wait(&lock); // Sleep on cond var WW--; // No longer waiting } AW++; • Can’t start because of readers, so go to sleep: AR = 2, WR = 0, AW = 0, WW = 1 • Finally, R3 comes along: AR = 2, WR = 1, AW = 0, WW = 1 • Now, say that R2 finishes before R1: AR = 1, WR = 1, AW = 0, WW = 1 • Finally, last of first two readers (R1) finishes and wakes up writer: if (AR == 0 && WW > 0) // No other active readers okToWrite.signal(); // Wake up one writer
  • 15. Simulation(3) • When writer wakes up, get: AR = 0, WR = 1, AW = 1, WW = 0 • Then, when writer finishes: if (WW > 0){ // Give priority to writers okToWrite.signal(); // Wake up one writer } else if (WR > 0) { // Otherwise, wake reader okToRead.broadcast(); // Wake all readers } • Writer wakes up reader, so get: AR = 1, WR = 0, AW = 0, WW = 0 • When reader completes, we are finished
  • 16. Questions • Can readers starve? Consider Reader() entry code: while ((AW + WW) > 0) { // Is it safe to read? WR++; // No. Writers exist okToRead.wait(&lock); // Sleep on cond var WR--; // No longer waiting } AR++; // Now we are active! • What if we erase the condition check in Reader exit? AR--; // No longer active if (AR == 0 && WW > 0) // No other active readers okToWrite.signal(); // Wake up one writer • Further, what if we turn the signal() into broadcast() AR--; // No longer active okToWrite.broadcast(); // Wake up one writer • Finally, what if we use only one condition variable (call it “okToContinue”) instead of two separate ones? • Both readers and writers sleep on this variable • Must use broadcast() instead of signal()
  • 17. Can we construct Monitors from Semaphores? • Locking aspect is easy: Just use a mutex • Can we implement condition variables this way? Wait() { semaphore.P(); } Signal() { semaphore.V(); } • Doesn’t work: Wait() may sleep with lock held • Does this work better? Wait(Lock lock) { lock.Release(); semaphore.P(); lock.Acquire(); } Signal() { semaphore.V(); } • No: Condition vars have no history, semaphores have history: • What if thread signals and no one is waiting? NO-OP • What if thread later waits? Thread Waits • What if thread V’s and noone is waiting? Increment • What if thread later does P? Decrement and continue
  • 18. Construction of Monitors from Semaphores • Problem with previous try: • P and V are commutative – result is the same no matter what order they occur • Condition variables are NOT commutative • Does this fix the problem? Wait(Lock lock) { lock.Release(); semaphore.P(); lock.Acquire(); } Signal() { if semaphore queue is not empty semaphore.V(); } • Not legal to look at contents of semaphore queue • There is a race condition – signaler can slip in after lock release and before waiter executes semaphore.P() • It is actually possible to do this correctly • Complex solution for Hoare scheduling in book • Can you come up with simpler Mesa-scheduled solution?
  • 19. Monitor Conclusion • Monitors represent the logic of the program • Wait if necessary • Signal when change something so any waiting threads can proceed • Basic structure of monitor-based program: lock while (need to wait) { condvar.wait(); } unlock do something so no need to wait lock condvar.signal(); unlock Check and/or update state variables Wait if necessary Check and/or update state variables
  • 20. C-Language Support for Synchronization • C language: Pretty straightforward synchronization • Just make sure you know all the code paths out of a critical section int Rtn() { lock.acquire(); … if (exception) { lock.release(); return errReturnCode; } … lock.release(); return OK; } • Watch out for setjmp/longjmp! • Can cause a non-local jump out of procedure • In example, procedure E calls longjmp, poping stack back to procedure B • If Procedure C had lock.acquire, problem! Proc A Proc B Calls setjmp Proc C lock.acquire Proc D Proc E Calls longjmp Stackgrowth
  • 21. C++ Language Support for Synchronization • Languages with exceptions like C++ • Languages that support exceptions are problematic (easy to make a non-local exit without releasing lock) • Consider: void Rtn() { lock.acquire(); … DoFoo(); … lock.release(); } void DoFoo() { … if (exception) throw errException; … } • Notice that an exception in DoFoo() will exit without releasing the lock
  • 22. C++ Language Support for Synchronization • Must catch all exceptions in critical sections • Catch exceptions, release lock, and re-throw exception: void Rtn() { lock.acquire(); try { … DoFoo(); … } catch (…) { // catch exception lock.release(); // release lock throw; // re-throw the exception } lock.release(); } void DoFoo() { … if (exception) throw errException; … } • Even Better: auto_ptr<T> facility. See C++ Spec. • Can deallocate/free lock regardless of exit method
  • 23. Java Language Support for Synchronization • Java has explicit support for threads and thread synchronization • Bank Account example: class Account { private int balance; // object constructor public Account (int initialBalance) { balance = initialBalance; } public synchronized int getBalance() { return balance; } public synchronized void deposit(int amount) { balance += amount; } } • Every object has an associated lock which gets automatically acquired and released on entry and exit from a synchronized method.
  • 24. Java Language Support for Synchronization • Java also has synchronized statements: synchronized (object) { … } • Since every Java object has an associated lock, this type of statement acquires and releases the object’s lock on entry and exit of the body • Works properly even with exceptions: synchronized (object) { … DoFoo(); … } void DoFoo() { throw errException; }
  • 25. Java Language Support for Synchronization • In addition to a lock, every object has a single condition variable associated with it • How to wait inside a synchronization method of block: • void wait(long timeout); // Wait for timeout • void wait(long timeout, int nanoseconds); //variant • void wait(); • How to signal in a synchronized method or block: • void notify(); // wakes up oldest waiter • void notifyAll(); // like broadcast, wakes everyone • Condition variables can wait for a bounded length of time. This is useful for handling exception cases: t1 = time.now(); while (!ATMRequest()) { wait (CHECKPERIOD); t2 = time.new(); if (t2 – t1 > LONG_TIME) checkMachine(); } • Not all Java VMs equivalent! • Different scheduling policies, not necessarily preemptive!