UNIT 3
What is a semaphore? Explain how semaphores can be used to deal with
Semaphore n-process critical section.
Ans: semaphore is a hardware-based solution to the critical section problem.
A Semaphore S is a integer variable that, apart from initialization is accessed only
through two standard atomic operations: wait() and signal().
The wait () operation is termed as P and signal () was termed as V
Definition of wait () is
Wait (S) {
While S <= 0
; S--;
}
Definition of signal () is
Signal (S) {
S++;
}
All modifications to the integer value of the semaphore in the wait () and signal()
operations must be executed indivisibly, that is when one process modifies the
semaphore value, no other process can simultaneously modify that same semaphore
value.
Usage:
Operating systems often distinguish between counting and binary semaphores. The
value of counting semaphore can range over an unrestricted domain and the binary
semaphore also known as mutex locks which provide mutual exclusion can range only
between 0 and 1. Binary semaphores are used to deal with critical-section problem for
multiple processes as n processes share a semaphore mutex initialized to 1.
do {
Wait (mutex) ;
// critical section
Signal (mutex);
// remainder section
} while (TRUE);
Counting semaphores can be used to control access to a given resource consisting of a
finite number of instances. Each process that wishes to use a resource performs a wait
() operation on the semaphore. When the count for the semaphore goes to 0, all
resources are being used. And the process that wish to use a resource will block until
the count becomes greater than 0.
Implementation:
The main disadvantage of the semaphore is that it requires busy waiting. Busy waiting
wastes CPU cycles that some other process might be able to use productively. This
type of semaphore is also called a spinlock because the process spins while waiting for
the lock. To overcome the need for busy waiting, we can modify the definition of wait
() and Signal () semaphore operations.
When the process executes the wait () operation and finds that the semaphore
value is not positive it must wait. Rather that engaging in busy waiting the process can
block itself. The block operation places a process into a waiting queue associated with
the semaphore and the state of the process is switched to the waiting state.
The process that is blocked waiting on a semaphore S should be restarted when
some other process executes a signal () operation, the process is restarted by a wakeup
() operation.
Definition of semaphore as a C struct
typedef struct {
int value;
struct process *list;
} semaphore;