Chapter 7: Process Synchronization
Chapter 7: Process Synchronization
1. Background
2. The Critical-Section Problem
3. Synchronization Hardware
4. Semaphores
5. Classical Problems of Synchronization
6. Critical Regions
7. Monitors
8. Synchronization in Solaris 2 & Windows 2000
#define BUFFER_SIZE 10
typedef struct {
...
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int counter = 0;
Shared variables
boolean flag[2];
initially flag [0] = flag [1] = false.
flag [i] = true ⇒ Pi ready to enter its critical section
Process Pi
do {
flag[i] := true;
while (flag[j]) ;
critical section
flag [i] = false;
remainder section
} while (1);
do {
choosing[i] = true;
number[i] = max(number[0], number[1], ;, number [n – 1])+1;
choosing[i] = false;
for (j = 0; j < n; j++) {
while (choosing[j])
;
while ((number[j] != 0) && (number[j,j] < number[i,i]))
;
}
critical section
number[i] = 0;
remainder section
} while (1);
return rv;
}
Shared data:
boolean lock = false;
Process Pi
do {
while (TestAndSet(lock)) ;
critical section
lock = false;
remainder section
}
Process Pi
do {
key = true;
while (key == true)
Swap(lock,key);
critical section
lock = false;
remainder section
}
Shared data:
semaphore mutex; //initially mutex = 1
Process Pi:
do {
wait(mutex);
critical section
signal(mutex);
remainder section
} while (1);
signal(S):
S.value++;
if (S.value <= 0) {
remove a process P from S.L;
wakeup(P);
}
wait(S1); wait(S1);
C--; C ++;
if (C < 0) { if (C <= 0)
signal(S1); signal(S2);
wait(S2); else
} signal(S1);
signal(S1);
Bounded-Buffer Problem
Dining-Philosophers Problem
Philosopher i:
do {
wait(chopstick[i])
wait(chopstick[(i+1) % 5])
; This solution may cause Deadlock.
eat Solutions:
; Allow at most 4 Philosophers.
signal(chopstick[i]);
Pick only when the 2 chopstick are
signal(chopstick[(i+1) % 5]); available
; Use asymmetric solution (old
think Philosopher pick first).
;
} while (1);
monitor monitor-name
{
shared variable declarations
procedure body P1 (;) {
...
}
procedure body P2 (;) {
...
}
procedure body Pn (;) {
...
}
{
initialization code
}
}
Operating System Concepts 7.34 Silberschatz, Galvin and Gagne 2002
Monitors
Variables
semaphore mutex; // (initially = 1)
semaphore next; // (initially = 0)
int next-count = 0;
x-count++;
if (next-count > 0)
signal(next);
else
signal(mutex);
wait(x-sem);
x-count--;
if (x-count > 0) {
next-count++;
signal(x-sem);
wait(next);
next-count--;
}