Module 7a: Classic Synchronization

advertisement
Module 7a: Classic Synchronization
n Background
n The Critical-Section Problem
n Synchronization Hardware
n Semaphores
n Classical Problems of Synchronization
n Monitors
Operating System Concepts with Java
Silberschatz, Galvin and Gagne ©2003
7a.1
Shared Resources
R1
P1
...
R2
P2
...
Rm
Pn
Concurrent Processes
Operating System Concepts with Java
7a.2
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
1
Background
n Concurrent access to shared data may result in data
inconsistency
n Maintaining data consistency requires mechanisms to ensure
the orderly execution of cooperating processes
n Shared-memory solution to bounded-butter problem (Chapter 4)
has a race condition on the class data count.
Operating System Concepts with Java
7a.3
Silberschatz, Galvin and Gagne ©2003
Race Condition
The Producer calls
while (1) {
while (count == BUFFER_SIZE)
; // do nothing
// produce an item and put in nextProduced
buffer[in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
}
Operating System Concepts with Java
7a.4
Silberschatz, Galvin and Gagne ©2003
2
Race Condition
The Consumer calls
while (1) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
// consume the item in nextConsumed
}
Operating System Concepts with Java
7a.5
Silberschatz, Galvin and Gagne ©2003
Race Condition
n count++ could be implemented as
register1 = count
register1 = register1 + 1
count = register1
n count-- could be implemented as
register2 = count
register2 = register2 - 1
count = register2
n Consider this execution interleaving:
S0: producer execute register1 = count {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = count {register2 = 5}
S3: consumer execute register2 = register2 - 1 {register2 = 4}
S4: producer execute count = register1 {count = 6 }
S5: consumer execute count = register2 {count = 4}
Operating System Concepts with Java
7a.6
Silberschatz, Galvin and Gagne ©2003
3
Example of Race Condition
Process P:
a=a+1
EndProcess;
a = 100
1. LOAD A, R1
2. INC R1, 1
3. STO R1, A
1, 4, 5, 6, 2, 3
Operating System Concepts with Java
Process Q:
a=a+2
EndProcess;
4. LOAD A, R1
5. INC R1, 2
6. STO R1, A
a = 101 and not 103.
7a.7
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
Critical Section
• Portion of a process’ code where shared
resources are accessed.
• For consistency, at most one process should
be in its critical section at the same time.
Operating System Concepts with Java
7a.8
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
4
Solution to Critical-Section Problem
1. Mutual Exclusion - If process Pi is executing in its critical
section, then no other processes can be executing in their
critical sections
2. Progress - If no process is executing in its critical section and
there exist some processes that wish to enter their critical
section, then the selection of the processes that will enter the
critical section next cannot be postponed indefinitely
3. Bounded Waiting - A bound must exist on the number of times
that other processes are allowed to enter their critical sections
after a process has made a request to enter its critical section
and before that request is granted
—
—
Assume that each process executes at a nonzero speed
No assumption concerning relative speed of the N processes
Operating System Concepts with Java
7a.9
Silberschatz, Galvin and Gagne ©2003
Types of Solutions for Mutual Exclusion
n Busy Wait: processes keep constantly checking if it is safe
to enter the CS.
n Sleep and Wakeup: processes are put to sleep when they
attempt to enter CS and another process is there already.
When a process leaves CS it wakes up the first process
waiting to get into CS.
Operating System Concepts with Java
7a.10
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
5
Busy Waiting
P
P
P
process P is wasting cycles checking
if it is safe to enter CS.
process P is suspended.
Operating System Concepts with Java
7a.11
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
Sleep and Wakeup
P
P
1
2
1
2
process P detects that it can’t enter CS and
is put to sleep.
process P is awaken and enters CS.
process P is suspended.
Operating System Concepts with Java
7a.12
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
6
A Busy Wait Solution
Test Set and Lock (TSL) Instruction
TSL instruction:
1
step 2
step 1
Register
Memory
Position
Operating System Concepts with Java
7a.13
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
Mutual Exclusion with TSL
Process P:
----EnterCS ( );
critical section
code;
LeaveCS ( );
EnterCS :
TSL R, FLAG | R←Flag;Flag ←1
CMP R, 0
| was Flag = 0?
JNZ EnterCS | if != 0 loop
RET
EndProcess;
| return; CS entered
LeaveCS:
MOV FLAG, 0 | Flag ←0
RET
| return; leave CS
Operating System Concepts with Java
7a.14
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
7
Two-task Solution
n Two tasks, T0 and T1 (Ti and Tj)
n Three solutions presented. All implement this MutualExclusion
interface:
public interface MutualExclusion
{
public static final int TURN 0 = 0;
public static final int TURN 1 = 1;
public abstract void enteringCriticalSection(int turn);
public asbtract void leavingCriticalSection(int turn);
}
Operating System Concepts with Java
7a.15
Silberschatz, Galvin and Gagne ©2003
Algorithm Factory class
Used to create two threads and to test each algorithm
public class AlgorithmFactory
{
public static void main(String args []) {
MutualExclusion alg = new Algorithm 1();
Thread first = new Thread( new Worker("Worker 0", 0, alg));
Thread second = new Thread(new Worker("Worker 1", 1, alg));
first.start();
second.start();
}
}
Operating System Concepts with Java
7a.16
Silberschatz, Galvin and Gagne ©2003
8
Worker Thread
public class Worker implements Runnable
{
private String name;
private int id;
private MutualExclusion mutex;
public Worker(String name, int id, MutualExclusion mutex) {
this.name = name;
this.id = id;
this.mutex = mutex;
}
public void run() {
while (true) {
mutex.enteringCriticalSection(id);
MutualExclusionUtilities.criticalSection(name);
mutex.leavingCriticalSection(id);
MutualExclusionUtilities.nonCriticalSection(name);
}
}
}
Operating System Concepts with Java
7a.17
Silberschatz, Galvin and Gagne ©2003
Algorithm 1
n Threads share a common integer variable turn
n If turn==i, thread i is allowed to execute
n Does not satisfy progress requirement
l Why?
Operating System Concepts with Java
7a.18
Silberschatz, Galvin and Gagne ©2003
9
Algorithm 1
public class Algorithm_1 implements MutualExclusion
{
private volatile int turn;
public Algorithm 1() {
turn = TURN 0;
}
public void enteringCriticalSection(int t) {
while (turn != t)
Thread.yield();
}
public void leavingCriticalSection(int t) {
turn = 1 - t;
}
}
Operating System Concepts with Java
7a.19
Silberschatz, Galvin and Gagne ©2003
Algorithm 2
n Add more state information
l Boolean flags to indicate thread’s interest in entering critical
section
n Progress requirement still not met
l Why?
Operating System Concepts with Java
7a.20
Silberschatz, Galvin and Gagne ©2003
10
Algorithm 2
public class Algorithm_2 implements MutualExclusion
{
private volatile boolean flag0, flag1;
public Algorithm 2() {
flag0 = false; flag1 = false;
}
public void enteringCriticalSection(int t) {
if (t == 0) {
flag0 = true;
while(flag1 == true)
Thread.yield();
}
else {
flag1 = true;
while (flag0 == true)
Thread.yield();
}
}
// Continued On Next Slide
Operating System Concepts with Java
7a.21
Silberschatz, Galvin and Gagne ©2003
Algorithm 2 - cont
public void leavingCriticalSection(int t) {
if (t == 0)
flag0 = false;
else
flag1 = false;
}
}
Operating System Concepts with Java
7a.22
Silberschatz, Galvin and Gagne ©2003
11
Algorithm 3
n Combine ideas from 1 and 2
n Does it meet critical section requirements?
Operating System Concepts with Java
7a.23
Silberschatz, Galvin and Gagne ©2003
Algorithm 3
public class Algorithm_3 implements MutualExclusion
{
private volatile boolean flag0;
private volatile boolean flag1;
private volatile int turn;
public Algorithm_3() {
flag0 = false;
flag1 = false;
turn = TURN_0;
}
// Continued on Next Slide
Operating System Concepts with Java
7a.24
Silberschatz, Galvin and Gagne ©2003
12
Algorithm 3 - enteringCriticalSection
public void enteringCriticalSection(int t) {
int other = 1 - t;
turn = other;
if (t == 0) {
flag0 = true;
while(flag1 == true && turn == other)
Thread.yield();
}
else {
flag1 = true;
while (flag0 == true && turn == other)
Thread.yield();
}
}
// Continued on Next Slide
Operating System Concepts with Java
7a.25
Silberschatz, Galvin and Gagne ©2003
Algo. 3 – leavingingCriticalSection()
public void leavingCriticalSection(int t) {
if (t == 0)
flag0 = false;
else
flag1 = false;
}
}
Operating System Concepts with Java
7a.26
Silberschatz, Galvin and Gagne ©2003
13
Synchronization Hardware
n Many systems provide hardware support for critical
section code
n Uniprocessors – could disable interrupts
l Currently running code would execute without preemption
l Generally too inefficient on multiprocessor systems
4 Operating systems using this not broadly scalable
n Modern machines provide special atomic hardware
instructions
4 Atomic = non-interruptable
l Either test memory word and set value
l Or swap contents of two memory words
Operating System Concepts with Java
7a.27
Silberschatz, Galvin and Gagne ©2003
Data Structure for Hardware Solutions
public class HardwareData
{
private boolean data;
public HardwareData(boolean data) {
this.data = data;
}
public boolean get() {
return data;
}
public void set(boolean data) {
this.data = data;
}
// Continued on Next Slide
Operating System Concepts with Java
7a.28
Silberschatz, Galvin and Gagne ©2003
14
Data Structure for Hardware Solutions - cont
public boolean getAndSet(boolean data) {
boolean oldValue = this.get();
this.set(data);
return oldValue;
}
public void swap(HardwareData other) {
boolean temp = this.get();
this.set(other.get());
other.set(temp);
}
}
Operating System Concepts with Java
7a.29
Silberschatz, Galvin and Gagne ©2003
Thread Using get-and-set Lock
// lock is shared by all threads
HardwareData lock = new HardwareData(false);
while (true) {
while (lock.getAndSet(true))
Thread.yield();
criticalSection();
lock.set(false);
nonCriticalSection();
}
Operating System Concepts with Java
7a.30
Silberschatz, Galvin and Gagne ©2003
15
Thread Using swap Instruction
// lock is shared by all threads
HardwareData lock = new HardwareData(false);
// each thread has a local copy of key
HardwareData key = new HardwareData(true);
while (true) {
key.set(true);
do {
lock.swap(key);
}
while (key.get() == true);
criticalSection();
lock.set(false);
nonCriticalSection();
}
Operating System Concepts with Java
7a.31
Silberschatz, Galvin and Gagne ©2003
Semaphores
n Integer variable with values 0, 1, ....
n Two operations (implemented by the OS):
l Down (acquire or P)
l Up (release or V)
n Value of semaphore can only be changed through up or down
and cannot be read directly.
Operating System Concepts with Java
7a.32
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
16
Semaphores
n Down (s);
l if s > 0
then s = s - 1
else put process that issued down to sleep in
the queue for semaphore s.
(this definition of Down does not allow negative values for s; other
definitions (see book) allow negative values.)
n Up (s);
l s = s + 1;
l if there is a process P waiting for s, awake P and make s = 0.
Operating System Concepts with Java
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
7a.33
Semaphore Table
n Maintained by the OS
Semaphore. Id. Value Queue
001
2
002
0
003
4
Operating System Concepts with Java
P1
7a.34
P2
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
17
Solution to the Mutual Exclusion
Problem with Semaphores
Process Q;
semaphore mutex=1;
Process P;
semaphore mutex=1;
down (mutex);
CriticalSection_Q;
up (mutex);
EndProcess;
down (mutex);
CriticalSection_P;
up (mutex);
EndProcess;
Operating System Concepts with Java
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
7a.35
Semaphores are Error-Prone!
Process P;
Process Q;
semaphore mutex=1;
semaphore mutex=1;
up (mutex);
CriticalSection_Q;
down (mutex);
EndProcess;
down (mutex);
CriticalSection_P;
up (mutex);
EndProcess;
Operating System Concepts with Java
7a.36
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
18
Synchronization Problems
n Processes share resources and need to coordinate their actions
before
shared
buffer
Producer
Operating System Concepts with Java
Consumer
7a.37
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
The Producer-Consumer Problem
shared
buffer
Producer
Consumer
• The Producer should not attempt to put an item into the buffer
when it is full (synchronization).
• The Consumer should not attempt to remove an item from the
buffer when it is empty (synchronization).
• The Producer and Consumer should not write/read into/from
the buffer at the same time (mutual exclusion).
Operating System Concepts with Java
7a.38
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
19
A Solution to the Producer-Consumer with
Semaphores
semaphore mutex = 1; /* controls access to CS */
semaphore empty=N; /* counts empty slots */
semaphore full=0;
/* counts full slots
*/
Process Producer ( );
Process Consumer ( );
while true do {
while true do {
produce_item;
down (full);
down (empty);
down (mutex);
down (mutex);
remove_item;
put_item;
up (mutex);
up (mutex);
up (empty);
up (full);
}
}
EndProcess;
EndProcess;
Operating System Concepts with Java
7a.39
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
An Incorrect Solution to the Producer-Consumer
Problem with Semaphores!
semaphore mutex = 1; /* controls access to CS */
semaphore empty=N; /* counts empty slots */
semaphore full=0;
/* counts full slots
*/
Process Producer ( );
Process Consumer ( );
while true do {
while true do {
produce_item;
down (mutex);
down (empty);
down (full);
down (mutex);
remove_item;
put_item;
up (mutex);
up (mutex);
up (empty);
up (full);
}
}
EndProcess;
EndProcess;
Operating System Concepts with Java
7a.40
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
20
The consumer runs first with an empty buffer and goes to sleep on down
(full). The producer goes to sleep on down(mutex).
semaphore mutex = 1; /* controls access to CS */
semaphore empty=N; /* counts empty slots */
semaphore full=0;
/* counts full slots
*/
Process Producer ( );
Process Consumer ( );
while true do {
while true do {
produce_item;
down (mutex);
down (empty);
down (full);
down (mutex);
remove_item;
put_item;
up (mutex);
up (mutex);
up (empty);
up (full);
}
}
EndProcess;
EndProcess;
Operating System Concepts with Java
7a.41
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
An Incorrect Solution to the Producer-Consumer
Problem with Semaphores!
A deadlock has occurred. Both the producer
and consumer are put to sleep and will
never wakeup.
Operating System Concepts with Java
7a.42
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
21
Semaphore
n Synchronization tool that does not require busy waiting
(spin lock)
n Semaphore S – integer variable
n Two standard operations modify S: acquire() and release()
l Originally called P() and V()
n Less complicated
n Can only be accessed via two indivisible (atomic) operations
acquire(S) {
while S <= 0
; // no-op
S--;
}
release(S) {
S++;
}
Operating System Concepts with Java
7a.43
Silberschatz, Galvin and Gagne ©2003
Semaphore as General Synchronization Tool
n Counting semaphore – integer value can range over an
unrestricted domain
n Binary semaphore – integer value can range only between 0
and 1; can be simpler to implement
l Also known as mutex locks
n Can implement a counting semaphore S as a binary semaphore
n Provides mutual exclusion
Semaphore S; // initialized to 1
acquire(S);
criticalSection();
release(S);
Operating System Concepts with Java
7a.44
Silberschatz, Galvin and Gagne ©2003
22
Synchronization using Semaphores
Implementation - Worker
public class Worker implements Runnable
{
private Semaphore sem ;
private String name;
public Worker(Semaphore sem , String name) {
this.sem = sem ;
this.name = name;
}
public void run() {
while (true) {
sem.acquire();
MutualExclusionUtilities.criticalSection(name);
sem.release();
MutualExclusionUtilities.nonCriticalSection(name);
}
}
}
Operating System Concepts with Java
7a.45
Silberschatz, Galvin and Gagne ©2003
Synchronization using Semaphores
Implementation - SemaphoreFactory
public class SemaphoreFactory
{
public static void main(String args []) {
Semaphore sem = new Semaphore(1);
Thread[] bees = new Thread[5];
for (int i = 0; i < 5; i++)
bees[i] = new Thread(new Worker
(sem , "Worker " + (new Integer(i)).toString() ));
for (int i = 0; i < 5; i++)
bees[i].start();
}
}
Operating System Concepts with Java
7a.46
Silberschatz, Galvin and Gagne ©2003
23
Semaphore Implementation
acquire(S){
value--;
if (value < 0) {
add this process to list
block;
}
}
release(S){
value++;
if (value <= 0) {
remove a process P from list
wakeup(P);
}
}
Operating System Concepts with Java
7a.47
Silberschatz, Galvin and Gagne ©2003
Semaphore Implementation
n Must guarantee that no two processes can execute acquire()
and release() on the same semaphore at the same time
n Thus implementation becomes the critical section problem
l Could now have busy waiting in critical section implementation
4 But implementation code is short
4 Little busy waiting if critical section rarely occupied
l Applications may spend lots of time in critical sections
4 Performance issues addressed throughout this lecture
Operating System Concepts with Java
7a.48
Silberschatz, Galvin and Gagne ©2003
24
Deadlock and Starvation
n Deadlock – two or more processes are waiting indefinitely for an
event that can be caused by only one of the waiting processes
n Let S and Q be two semaphores initialized to 1
P0
P1
acquire(S);
acquire(Q);
.
acquire(Q);
acquire(S);
.
.
.
release(S);
release(Q);
.
.
release(Q);
release(S);
n Starvation – indefinite blocking. A process may never be
removed from the semaphore queue in which it is suspended.
Operating System Concepts with Java
7a.49
Silberschatz, Galvin and Gagne ©2003
Classical Problems of Synchronization
n Bounded-Buffer Problem
n Readers and Writers Problem
n Dining-Philosophers Problem
Operating System Concepts with Java
7a.50
Silberschatz, Galvin and Gagne ©2003
25
Bounded-Buffer Problem
public class BoundedBuffer implements Buffer
{
private static final int BUFFER SIZE = 5;
private Object[] buffer;
private int in, out;
private Semaphore mutex;
private Semaphore empty;
private Semaphore full;
// Continued on next Slide
Operating System Concepts with Java
7a.51
Silberschatz, Galvin and Gagne ©2003
Bounded Buffer Constructor
public BoundedBuffer() {
// buffer is initially empty
in = 0;
out = 0;
buffer = new Object[BUFFER SIZE];
mutex = new Semaphore(1);
empty = new Semaphore(BUFFER SIZE);
full = new Semaphore(0);
}
public void insert(Object item) { /* next slides */ }
public Object remove() { /* next slides */ }
}
Operating System Concepts with Java
7a.52
Silberschatz, Galvin and Gagne ©2003
26
Bounded Buffer Problem: insert() Method
public void insert(Object item) {
empty.acquire();
mutex.acquire();
// add an item to the buffer
buffer[in] = item;
in = (in + 1) % BUFFER SIZE;
mutex.release();
full.release();
}
Operating System Concepts with Java
7a.53
Silberschatz, Galvin and Gagne ©2003
Bounded Buffer Problem: remove() Method
public Object remove() {
full.acquire();
mutex.acquire();
// remove an item from the buffer
Object item = buffer[out];
out = (out + 1) % BUFFER SIZE;
mutex.release();
empty.release();
return item;
}
Operating System Concepts with Java
7a.54
Silberschatz, Galvin and Gagne ©2003
27
Bounded Buffer Problem: Producer
import java.util.Date;
public class Producer implements Runnable
{
private Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
Date message;
while (true) {
// nap for awhile
SleepUtilities.nap();
// produce an item & enter it into the buffer
message = new Date();
buffer.insert(message);
}
}
}
Operating System Concepts with Java
7a.55
Silberschatz, Galvin and Gagne ©2003
Bounded Buffer Problem: Consumer
import java.util.Date;
public class Consumer implements Runnable
{
private Buffer buffer;
public Consumer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
Date message;
while (true) {
// nap for awhile
SleepUtilities.nap();
// consume an item from the buffer
message = (Date)buffer.remove();
}
}
}
Operating System Concepts with Java
7a.56
Silberschatz, Galvin and Gagne ©2003
28
Bounded Buffer Problem: Factory
public class Factory
{
public static void main(String args []) {
Buffer buffer = new BoundedBuffer();
// now create the producer and consumer threads
Thread producer = new Thread(new Producer(buffer));
Thread consumer = new Thread(new Consumer(buffer));
producer.start();
consumer.start();
}
}
Operating System Concepts with Java
7a.57
Silberschatz, Galvin and Gagne ©2003
Readers-Writers Problem: Reader
public class Reader implements Runnable
{
private RWLock db;
public Reader(RWLock db) {
this.db = db;
}
public void run() {
while (true) { // nap for awhile
db.acquireReadLock();
// you now have access to read from the database
// read from the database
db.releaseReadLock();
}
}
}
Operating System Concepts with Java
7a.58
Silberschatz, Galvin and Gagne ©2003
29
Readers-Writers Problem: Writer
public class Writer implements Runnable
{
private RWLock db;
public Writer(RWLock db) {
this.db = db;
}
public void run() {
while (true) {
db.acquireWriteLock();
// you have access to write to the database
// write to the database
db.releaseWriteLock();
}
}
}
Operating System Concepts with Java
7a.59
Silberschatz, Galvin and Gagne ©2003
Readers-Writers Problem: Interface
public interface RWLock
{
public abstract void acquireReadLock();
public abstract void acquireWriteLock();
public abstract void releaseReadLock();
public abstract void releaseWriteLock();
}
Operating System Concepts with Java
7a.60
Silberschatz, Galvin and Gagne ©2003
30
Readers-Writers Problem: Database
public class Database implements RWLock
{
private int readerCount;
private Semaphore mutex;
private Semaphore db;
public Database() {
readerCount = 0;
mutex = new Semaphore(1);
db = new Semaphore(1);
}
public int acquireReadLock() { /* next slides */ }
public int releaseReadLock() {/* next slides */ }
public void acquireWriteLock() {/* next slides */ }
public void releaseWriteLock() {/* next slides */ }
}
Operating System Concepts with Java
7a.61
Silberschatz, Galvin and Gagne ©2003
Readers-Writers Problem: Methods called by readers
public void acquireReadLock() {
mutex.acquire();
++readerCount;
// if I am the first reader tell all others
// that the database is being read
if (readerCount == 1)
db.acquire();
mutex.release();
}
public void releaseReadLock() {
mutex.acquire();
--readerCount;
// if I am the last reader tell all others
// that the database is no longer being read
if (readerCount == 0)
db.release();
mutex.release();
}
Operating System Concepts with Java
7a.62
Silberschatz, Galvin and Gagne ©2003
31
Readers-Writers Problem: Methods called by writers
public void acquireWriteLock() {
db.acquire();
}
public void releaseWriteLock() {
db.release();
}
Operating System Concepts with Java
7a.63
Silberschatz, Galvin and Gagne ©2003
Dining-Philosophers Problem
n Shared data
Semaphore chopStick[] = new Semaphore[5];
Operating System Concepts with Java
7a.64
Silberschatz, Galvin and Gagne ©2003
32
Dining-Philosophers Problem (Cont.)
n
Philosopher i:
while (true) {
// get left chopstick
chopStick[i].acquire();
// get right chopstick
chopStick[(i + 1) % 5].acquire();
eating();
// return left chopstick
chopStick[i].release();
// return right chopstick
chopStick[(i + 1) % 5].release();
thinking();
}
Operating System Concepts with Java
7a.65
Silberschatz, Galvin and Gagne ©2003
Monitors
n Variables + procedures
n Monitor variables can only be manipulated by monitor
procedures
n There can be at most one process executing a monitor
procedure
mutual exclusion on monitor
variables is guaranteed.
Operating System Concepts with Java
7a.66
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
33
Monitors (cont’d)
n Condition Variables + two operations:
l wait (c): removes process from monitor and places it in a waiting
queue for condition c.
l signal (c): takes the first process in the queue for condition c and
puts it back into the monitor. The process that does a signal has to
leaves the monitor
signal has to be the last statement of a monitor
procedure.
Operating System Concepts with Java
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
7a.67
Monitors
queue for c1
queue for c2
first time entry queue
Operating System Concepts with Java
Monitor X;
int a, b,c;
cond c1, c2;
Procedure P1( );
a=a+1
if a > 0 then wait (c1);
....
End; /* P1 */
Procedure P2 ( );
.....
signal (c1)
End; /* P2 */
7a.68
normal
exit
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
34
The Producer-Consumer Problem with
Monitors
Monitor ProducerConsumer
condition full, empty;
int count;
Procedure EnterItem;
{ if count == N then wait (full);
enter_item;
count = count + 1;
if count == 1 then signal (empty);
}
Operating System Concepts with Java
7a.69
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
The Producer-Consumer Problem with
Monitors
Procedure RemoveItem;
{ if count == 0 then wait (empty);
remove_item;
count = count - 1;
if count == N - 1 then signal (full);
}
EndMonitor;
Operating System Concepts with Java
7a.70
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
35
The Producer-Consumer Problem with
Monitors
Procedure Producer;
{ while true
{generate_item;
ProduceConsumer.EnterItem; } ;
};
Procedure Consumer;
{ while true
{ProduceConsumer.RemoveItem ;
consume_item;} ;
}
Operating System Concepts with Java
7a.71
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
Monitors
n A monitor is a high-level abstraction that provides thread safety
n Only one thread may be active within the monitor at a time
monitor monitor-name
{
// variable declarations
public entry p1(…) {
…
}
public entry p2(…) {
…
}
}
Operating System Concepts with Java
7a.72
Silberschatz, Galvin and Gagne ©2003
36
Condition Variables
n condition x, y;
n A thread that invokes x.wait is suspended until another thread
invokes x.signal
Operating System Concepts with Java
7a.73
Silberschatz, Galvin and Gagne ©2003
Monitor with condition variables
Operating System Concepts with Java
7a.74
Silberschatz, Galvin and Gagne ©2003
37
Implementing Monitors with Semaphores
Monitor:
• mutual exclusion
• condition variable
Operating System Concepts with Java
7a.75
binary semaphore
one binary
semaphore per
condition variable
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
Implementing Monitors with Semaphores
semaphore mutex=1; /* enforces mutual exclusion on monitor */
semaphore c1, c2, ..., cn = 0; /* simulate n condition variables */
int q1, ..., qn = 0; /* queue length for cond. variables c1, ..., cn */
void EnterMonitor (void);
{ down(mutex) };
void LeaveNormally (void);
{ up (mutex) };
void LeaveWithSignal (c);
{ if qc != 0 { qc = qc - 1; up (c);}
else up ( mutex);
}
void Wait (c);
{ qc = qc + 1 ;
up (mutex); down (c); }
Operating System Concepts with Java
7a.76
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
38
Implementing Monitors with Semaphores
Monitor ProducerConsumer
condition full, empty;
int count;
while true {
GenerateItem ();
EnterMonitor ();
if count = = N then Wait(full);
enter_item();
count = count + 1;
if (count == 1) then
LeaveWithSignal (empty);
else LeaveNormally ();
}
Procedure EnterItem;
{ if count == N then wait (full);
enter_item;
count = count + 1;
if count = = 1 then signal (empty);
}
producer with simulated
monitor
monitor solution
Operating System Concepts with Java
7a.77
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
Implementing Monitors with Semaphores
while true {
EnterMonitor ();
if count = = 0 then Wait(empty);
remove_item();
count = count - 1;
if count = = N - 1 then
LeaveWithSignal (full);
else LeaveNormally ();
}
Procedure RemoveItem;
{ if count == 0 then wait (empty);
remove_item;
count = count - 1;
if count = = N - 1 then signal (full);
}
EndMonitor;
consumer with simulated
monitor
monitor solution
Operating System Concepts with Java
7a.78
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
39
Implementing Monitors with Semaphores
When a process P does a Wait (c), mutex is left with the value 1.
Then, another process can execute an EnterMonitor and signal
the waiting process.
mutex=1
c=0
process Q
process P
(1)
EnterMonitor();
---(2)
Wait (c);
----
mutex=0
mutex=1
P sleeps
(3)
mutex=0
(4)
EnterMonitor();
------LeaveWithSignal(c);
P is awakened
c=0
Operating System Concepts with Java
7a.79
Silberschatz,
and Gagne ©2003
©
2004 D.A. Galvin
Menascé
Condition Variable Solution to Dining Philosophers
monitor DiningPhilosophers {
int[] state = new int[5];
static final int THINKING = 0;
static final int HUNGRY = 1;
static final int EATING = 2;
condition[] self = new condition[5];
public diningPhilosophers {
for (int i = 0; i < 5; i++)
state[i] = THINKING;
}
public entry pickUp(int i) {
state[i] = HUNGRY;
test(i);
if (state[i] != EATING)
self[i].wait;
}
// Continued on Next Slide
Operating System Concepts with Java
7a.80
Silberschatz, Galvin and Gagne ©2003
40
Solution to Dining Philosophers (cont)
public entry putDown(int i) {
state[i] = THINKING;
// test left and right neighbors
test((i + 4) % 5);
test((i + 1) % 5);
}
private test(int i) {
if ( (state[(i + 4) % 5] != EATING) &&
(state[i] == HUNGRY) &&
(state[(i + 1) % 5] != EATING) ) {
state[i] = EATING;
self[i].signal;
}
}
Operating System Concepts with Java
7a.81
Silberschatz, Galvin and Gagne ©2003
41
Download