Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Semaphores
Contents
Review
of race conditions
Library analogy to demonstrate
resource contention
Introduction to semaphores
Thread 2:
a = data;
a = a+1;
data = a;
b = data;
b = b + 1;
data = b;
Thread 1
Thread 2
a =
data;
--a = a+1; --data =
a;
---
dat
a
0
0
1
Thread 1
Thread 2
a =
data;
--a = a+1; b = data;
data =
a;
---
dat
a
0
0
1
Solutions?
Locks
What
Library Analogy
emp
ty
Library Analogy
What
is known:
is not known:
Library Analogy
emp
ty
Study
rooms resources
Students processes
Front desk semaphore
Semaphores
By
Semaphores
Synchronization
Semaphore,
tool
integer variable
atomic increment and decrement
waiting list
Two
wait()
signal()
S
Semaphores
typedef struct{
int value;
process *list;
} semaphore;
wait(S) {}
block() {}
signal(S) {}
wakeup(P) {}
wait()
Decrements
S value
If the value is negative, adds
requesting process to waiting list
and blocks the requesting process
wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add process to S->list;
block();
}
}
signal()
Increments
S value
If the value is not positive, removes
a process from waiting list and
wakes it up
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove process P from S->list;
wakeup(P);
}
}
Types of Semaphores
Counting
semaphore
Binary semaphore
Value can be only 1 or 0
Known as mutex
Constructed from counting
semaphore by initializing value to 1
Provides mutual exclusion
Binary Semaphore
semaphore mutex(1);
while(TRUE) {
wait(mutex);
// critical section of code to lock
signal(mutex);
// continue code
}
Does
Applications of
Semaphores
Bounded-Buffer
Problem
Readers and Writers Problem
Dining-Philosophers Problem